Select all given sibling elements between two other given sibling elements in JavaScript
Selecting all given sibling elements between two other given sibling elements in plain JavaScript + CSS.
Example: the color of text only of those paragraphs (but not divs) that are placed between the first and the second heading is set to red:
paragraph
div
First heading
div
paragraph
div
paragraph
Second heading
paragraph
div
Other heading
paragraph
div
HTML code:
<div class="example">
<p>paragraph</p>
<div>div</div>
<h2>First heading</h2>
<div>div</div>
<p>paragraph</p>
<div>div</div>
<p>paragraph</p>
<h2>Second heading</h2>
<p>paragraph</p>
<div>div</div>
<h2>Other heading</h2>
<p>paragraph</p>
<div>div</div>
</div>
JavaScript code:
<script>
var container = '.example';
var paragraph = 'p';
var heading_1 = 'h2:nth-of-type(1)';
var heading_2 = 'h2:nth-of-type(2)';
// var the_paragraphs = document.querySelectorAll( '.example h2:nth-of-type(1) ~ p:not( h2:nth-of-type(2) ~ p )' );
var the_paragraphs = document.querySelectorAll(' '+container+' '+heading_1+' ~ '+paragraph+':not( '+heading_2+' ~ '+paragraph+' ) ');
for ( var the_paragraph of the_paragraphs ) {
the_paragraph.classList.add('red');
}
</script>
CSS code:
.red {color: #c00;}
Browser support
- Windows
- Edge 12.0+
- Firefox 3.5+
- Google Chrome 1.0+
- Opera 10.0+
- Safari 3.1+
- Linux
- Firefox 3.5+
- Google Chrome 1.0+
- Opera 10.0+
- iOS
- Safari 2.0+
- Android
- Samsung Internet 1.0+
- Chrome Android 18.0+
- Firefox for Android 4.0+
- Opera Android 10.1+