0

I want to change the color of all elements with

  • tags to red.

    I'm doing:-

    document.getElementsByTagName("li").style.color = "red"
    

    This isn't working. But it's working with querySelectorAll method and getElementsByClassName method.

    Does it mean that I can't use this technique with getElementsByTagName or am I doing it wrong?

  • Gershom Maes
    • 7,358
    • 2
    • 35
    • 55
    • Duplicate [What do querySelectorAll and getElementsBy\* methods return?](https://stackoverflow.com/questions/10693845/what-do-queryselectorall-and-getelementsby-methods-return) – esqew Nov 10 '22 at 16:00

    3 Answers3

    0

    The return value of the getElementsByTagName() method is a HTMLCollection and not a DOM Element.

    You can iterate over the HTMLCollection in different ways. For example:

    const els = document.getElementsByTagName("li");
    for(const el of els) {
        el.style.color = "red";
    }
    
    0

    Try this:

    
        let listItems = [...document.getElementsByTagName("li")];
        listItems.forEach(li => li.style.color = "red");
    
    0

    Since the getElementsByTagName method returns a live HTMLCollection of elements, you need to iterate over the collection to apply your style.

    Please run the snippet below to see this in action:

    //declare function to change color of list items
    function changeColor() {
      //get li tags by tag name
      let li_tags = document.getElementsByTagName("li")
      //iterate over tags and apply the color red
      for (let i = 0; i < li_tags.length; i++) {
        li_tags[i].style.color = "red"
      }
    }
    
    //declare button as variable using the btn id
    const btn = document.getElementById("btn")
    
    //when button is clicked run the changeColor function
    btn.addEventListener("click", changeColor)
    <ul>
      <li>list item</li>
      <li>list item</li>
      <li>list item</li>
      <li>list item</li>
    </ul>
    <br />
    <button id="btn">Change Color</button>
    Aib Syed
    • 3,118
    • 2
    • 19
    • 30