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?

Answers:

Answer

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('#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.

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="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>

Answer

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>

Answer

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.