How to change or toggle class name of a child element from a parent element using javascript?

`<div class="box-5" id="firstselectionbox">
            <button class="firstselection highlighted" id="constructionbutton"onclick="toggleclassbox2(this)"value=1>Construction</button>
            <button class="firstselection" id="interiorbutton" onclick="toggleclassbox2(this)"value=2>Interiors</button>
        </div>

function toggleclassbox2(elm) {
      var helement = document.querySelector("#firstselectionbox");
      console.log(helement.childNodes);
} ` 

The last line helement.childNodes gives me the child elements, but I am unable to get the class List of child elements or toggle them. Please help.

10 thoughts on “How to change or toggle class name of a child element from a parent element using javascript?”

  1. To get to the attribute values of the class attribute of each of the <button> child elements of the <div> element, try:

    var helement = document.querySelectorAll("#firstselectionbox button");
    for (let he of helement)
    {
    target = he.getAttribute("class");
    console.log(target)
    }
    

    Output:

    "firstselection highlighted"
    "firstselection"
    
    Reply

Leave a Comment