Search code examples
javascriptdom-manipulation

Update css styles using getElementsByTagName


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?


  • Solution

  • 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>