如何用JS选择某个类型的下一个兄弟? [英] How to select next sibling of a certain type with JS?

查看:79
本文介绍了如何用JS选择某个类型的下一个兄弟?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些HTML

<h4 id="start-here">title</h4>
<p>paragraph</p>
<p>paragraph</p>
...some number of paragraphs... 
<a href="#" class="link">link</a>

我有< h4> 在JavaScript中选择了id。我如何从JS中的选择中获得第一个< a> 哪个属于类链接,或者只是下一个兄弟锚标记?

And I've got the <h4> with the id selected in JavaScript. How do I get from that selection in JS to the first <a> which is of the class link, or just the next sibling anchor tag?

推荐答案

使用 document.querySelector() 和CSS选择器,此处带有一般兄弟组合器 ,你可以这样做:

Using document.querySelector() and a CSS selector, here with the general sibling combinator ~, you can achieve that like this:

附注,在下面的示例中我以内联样式为目标,但通常更好地切换类。

Stack snippet

Stack snippet

(function(){

  document.querySelector('#stat-here ~ a.link').style.color = 'red';

})();

<h4 id="stat-here">title</h4>
<p>paragraph</p>
<a href="#">link</a>
<p>paragraph</p>
<a href="#" class="link">link</a>

根据其他问题/评论更新,如何获得多个元素作为回报。

Updated based on another question/comment, how to get more than one element in return.

使用 document.querySelectorAll() 可以做类似的事情,并针对这样的多个元素。

With document.querySelectorAll() one can do similar, and target multiple elements like this.

Stack snippet

Stack snippet

(function(){

  var elements = document.querySelectorAll('#div2, #div3');

  for (var i = 0; i < elements.length; i++) {
    elements[i].style.color = 'red';
  }

})();

<h4 id="stat-here1">title</h4>
<div id="div1">some text</div>

<h4 id="stat-here2">title</h4>
<div id="div2">some text</div>

<h4 id="stat-here3">title</h4>
<div id="div3">some text</div>

这篇关于如何用JS选择某个类型的下一个兄弟?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆