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:
- Check if there is an active class in the lielement after clicking it
- if there is none then add activeclass and if it already there thenreturnor do nothing
for 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
 
     
     
    
` so we can cater all of them at once. And tagName just gives you the HTML tag of an element [TagName](https://www.w3schools.com/jsref/prop_element_tagname.asp)
– HugeBelieve Oct 02 '19 at 03:24