Search code examples
javascriptpropertiesthemesanchor

Change child link color with javascript


I have webpage with a header and body and footer I put a script to change the theme from dark to light when switch button is clicked. But not all links have the same color, for example i want those of the header to be "white" and those of body to be "silver",

So for the header i have a definition like this :

#header a{color:black}
#header a:hover{color:red}

I could change the text color as :

var hdr = document.getElementById("header");
hdr.style.color = "#white";

My question is how to change the color of child "a" of element header with javascript the same way as i am doing it with header it self ?

Thanks.


Solution

  • As much asked from you - you want to select header id, and change all the a tags inside it.

    So, you're looking for the selector for the a tags inside the header id.

    Select all the a anchor tags, and change all tags with loop, to your desired color.

    let headerAnchorTags = hdr.getElementsByTagName('a'); //you have already selected hdr
            
    for(var i=0; i<headerAnchorTags.length; i++){
       headerAnchorTags[i].style.color = "black";
      }