I have a click event that adds an active class to the link's parentNode. On click the active class should be removed from the siblings of the parentNode. This is the code so far:
categories = document.querySelectorAll('.categories');
for(var i = 0; i < categories.length; i++) {
categories[i].onclick = function(e) {
// ('.categoriesparent').classList.remove('active');
this.parentNode.classList.add('active');
}
I tried the line that is commented out, and that breaks the adding of the class on click. Is there an equivalent to jQuery's siblings().removeClass('active')? Thanks for any help.
Here is the DOM for this section:
<div id="nav">
<span class="categoriesparent active">
<a class="categories">Link</a>
</span>
<span class="categoriesparent">
<a class="categories">Link2</a>
</span>
</div>
UPDATE - this is the original full code snippet:
<html>
<head></head>
<body>
<div id="nav">
<span class="categoriesparent">
<a href="#" class="categories">Link</a>
</span>
<br><br>
<span class="categoriesparent">
<a href="#" class="categories">Link2</a>
</span>
</div>
<script>
categories = document.querySelectorAll('.categories');
for(var i = 0; i < categories.length; i++) {
categories[i].onclick = function(e) {
// ('.categoriesparent').classList.remove('active');
this.parentNode.classList.add('active');
}
}
</script>
</body>
</html>
UPDATE after incorporating BRK's code snippet:
<html>
<head></head>
<body>
<div id="nav">
<span class="categoriesparent active">
<a href="#" class="categories">Link</a>
</span>
<br><br>
<span class="categoriesparent">
<a href="#" class="categories">Link2</a>
</span>
</div>
<script>
categories = document.querySelectorAll('.categories');
categories.forEach(function(cat, index) {
cat.onclick = function(e) {
document.querySelector('.categoriesparent.active').classList.remove('active');
this.parentNode.classList.add('active');
}
});
</script>
</body>
</html>