Costa Michailidis
Costa Michailidis

Reputation: 8188

How to select next sibling of a certain type with JS?

I've got some html

<h4 id="start-here">title</h4>
<p>paragraph</p>
<p>paragraph</p>
...some number of paragraphs... 
<a href="#" class="link">link</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?

Upvotes: 11

Views: 12370

Answers (3)

Asons
Asons

Reputation: 87303

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

A side note, in below samples I target inline style, though it is in general better to toggle a class.

Stack snippet

(function(){

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

})();
<h4 id="start-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.

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

Stack snippet

(function(){

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

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

})();
<h4 id="start-here1">title</h4>
<div id="div1">some text</div>

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

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

Upvotes: 14

Touffy
Touffy

Reputation: 6561

The "start-here" ID on your element makes this easy. But let's imagine you have a reference to a DOM element without such a convenient selector, and you don't want to add a temporary ID to it.

In that case, you could use XPath with document.evaluate and your DOM reference as the second argument. Let's say you have that reference in yourElement and you want the next <section> sibling

const nextSibling = document.evaluate("following-sibling::section", yourElement, null,
  XPathResult.FIRST_ORDERED_NODE_TYPE).singleNodeValue

Upvotes: 6

Kolzar
Kolzar

Reputation: 883

I think to start with the first sibling, then i put all the siblings inside an array. Hence I extract what you want.

var x = document.getElementById("stat-here");
console.log(x)
var result = [],
    node = x.nextSibling;

while ( node ) {
    if (node.nodeType === Node.ELEMENT_NODE ) {
     result.push( node );
    }
    node = node.nextElementSibling || node.nextSibling;
}
console.log(result, '\n Result: ',result[result.length-2])
<h4 id="stat-here">title</h4>
<p>paragraph</p>
<p>paragraph</p>
<a href="#" class="link">link</a>

Upvotes: 3

Related Questions