gpt4 book ai didi

Javascript::使用 querySelector 选择兄弟对象

转载 作者:行者123 更新时间:2023-11-30 10:04:33 26 4
gpt4 key购买 nike

标题几乎是不言自明的......

这是我的代码:

<div id=player>
<div class="button hand">&#9658;</div>
<div class=time>00:00/00:00</div>
<div class="timeline hand"><span class="now hand"></span></div>
</div>

我希望能够得到 <span class="now hand"></span><div class="timeline hand"></div> 之间通过querySelector

var now=document.querySelector('#player>_____________.now.hand');

我也在考虑是否有更方便的方法来根据 child 或 sibling 的编号从相对 ID 中选择对象,而不是使用 ID 或类名。

最佳答案

您使用标准后代选择器(#player.now.hand 之间的空格):

var text = document.querySelector("#player .now.hand").innerHTML;
var p = document.createElement('p');
p.innerHTML = "Text is '" + text + "'";
document.body.appendChild(p);
<div id=player>
<div class="button hand">&#9658;</div>
<div class=time>00:00/00:00</div>
<div class="timeline hand"><span class="now hand">text in now hand</span></div>
</div>

I'm also thinking if there is more convenient way to pick object from the relative id by children(s) or sibling(s) number instead of using id or class name.

如果这是在事件处理程序中(或您从引用某个元素开始的任何其他地方),是的,您可以使用 parentNode 来查找父节点(或重复查找祖先节点) ,您可以在元素上使用 querySelector 以仅在其中查找,等等。

例如:

document.body.addEventListener("click", function(e) {
var targetClass = e.target.className;
if (/\bbutton\b/.test(targetClass) && /\bhand\b/.test(targetClass)) {
alert(e.target.parentNode.querySelector(".now.hand").innerHTML);
}
}, false);
.button.hand {
color: blue;
font-weight: bold;
}
.now.hand {
color: green;
}
<div>
<div class="button hand">Click me</div>
<div class=time>00:00/00:00</div>
<div class="timeline hand"><span class="now hand">First hand</span></div>
</div>
<div>
<div class="button hand">Click me</div>
<div class=time>00:00/00:00</div>
<div class="timeline hand"><span class="now hand">Second hand</span></div>
</div>
<div>
<div class="button hand">Click me</div>
<div class=time>00:00/00:00</div>
<div class="timeline hand"><span class="now hand">Third hand</span></div>
</div>

关于Javascript::使用 querySelector 选择兄弟对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29867702/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com