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?
Advertisement
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('#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>