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
- Accessing the first element in forEach loop (JavaScript)
- Append an element after a specific element in JavaScript
- Array to string in JavaScript
- Calculate sum of HTML table column in JavaScript
- Detect if a class has been added (JavaScript)
- Detecting a newly generated element and adding a class to it in JavaScript
- Generating an HTML list out of page headings in JavaScript
- Get the current URL in JavaScript
- Getting the last class name in classList collection
- Removing the last character from a string in Javascript
- Transliterating Russian to English in JavaScript
- Wrap each character of a string in <span> tag (JavaScript)
- Wrap each word of text in <span> tag (JavaScript)