Reputation: 675
I read some topics about this before but this is the first time I try to apply it, but I got quite confused about how to check if some element has a class child and add some new class into it.
let say I want to add an active
class to a li
element child after click it. This is step by step that I want to do:
li
element after clicking itactive
class and if it already there then return
or do nothingfor number 1 I read this topic check-if-an-element-contains-a-class-in-javascript but I quite confused of how to check in a child
and for number 2 I already make the function for it but I quite confused where I must put it in my code
this is my html:
<li id="test" class="additional-menu"><a href="#">Link1</a>
<ul>
<li class="active"><a href="#" id="">Home</a></li>
<li><a href="#">Career</a></li>
<li><a href="#">Privacy Policy</a></li>
</ul>
</li>
this is my css:
.active{
color: red
}
this is my js to check the child:
// This is for check a normal class but I doesn't know how to check a child class element from this
function hasClass(element, cls) {
return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1;
}
var el = document.getElementById('test');
alert(hasClass(el, 'active'));
// I can use this function if it inside button using onClick
// But I got quite confused of how to use it without button
function addClass () {
var x = document.getElementsById("test")[0];
x.className += ' active';
}
Can someone help me to understand this? for your imagination, I want to make a navbar using this and the class still there when I move to a different routing let say if I'm in home
I want the class to stay in home
and if I'm in career
I want the class to stay in there. I feel like I already there to solved it but still no luck
Upvotes: 1
Views: 3130
Reputation: 322
document.addEventListener('DOMContentLoaded', ()=>{
// event attached to parent for getting clicks of all child while bubbling
document.querySelector(".parent").addEventListener("click", (event)=>{
event.preventDefault(); //prevent default "a" tag redirect
let target = event.target;
if(target.tagName != "A"){
return; // to make sure only <a> is been clicked
}
target = target.parentElement; //make related li as target now
for(let li of target.parentElement.children){ //all child of parent ul
li.classList.remove("active");
}
target.classList.add("active");
});
});
.active{
color: red
}
<li id="test" class="additional-menu"><a href="#">Link1</a>
<ul class="parent">
<li class="active"><a href="#" id="">Home</a></li>
<li><a href="#">Career</a></li>
<li><a href="#">Privacy Policy</a></li>
</ul>
</li>
Upvotes: 2