KOMPX.COM or COMPMISCELLANEA.COM   

Adding a class to all sibling elements of a specific type in JavaScript

Adding a class to all sibling div elements in a container in pure JavaScript.

Example:

A class of "red-background" is added to every div, immediate child of .example container, making their background red.

HTML code:


<div class="example">
	<div></div>
	<p></p>
	<div></div>
	<p></p>
</div>

JavaScript code:


<script>
var siblings = document.querySelectorAll('.example > div');

for (var i = 0; i < siblings.length; i++) {
	siblings[i].classList.add('red-background');
};
</script>

CSS code:


.red-background {background: #f00;}

Browser support
Windows
Internet Explorer 10.0+
Edge 12.0+
Firefox 3.6+
Google Chrome 8.0+
Opera 11.5+
Safari 5.1+
Linux
Firefox 3.6+
Google Chrome / Chromium
Opera 11.5+
More