Search code examples
javascriptgetelementsbyname

trying to toggle the color of some p tags using getElementsByName


This is what I have but I do not know how to target the different id for orange

function toggleColor(){
    document.getElementsByName("color").style.color = 'blue';
    document.getElementById().style.color = 'orange';
}


<ul>
    <li><p id="skg"name="color" onclick="toggleColor();">SKG</p></li>
    <li><p id="tech" name="color" onclick="toggleColor();">Tech</p></li>
    <li><p id="upd" name="color" onclick="toggleColor();">UPD</p></li>
</ul>

Solution

  • It is a really a bad practice attach the javascript events in the HTML so I recommend use the addEventListener function to do this. You will get the same result but with a clean HTML and a code easy to reuse and maintain.

    HTML

    <ul>
        <li><p name="colors" id="skg">SKG</p></li>
        <li><p name="colors" id="tech">Tech</p></li>
        <li><p name="colors" id="upd">UPD</p></li>
    </ul>
    

    JS

    var colors = document.getElementsByName('colors');
    for (var i = 0; i < colors.length; i ++ ){
      colors[i].addEventListener('click', toggleColor);
    }
    
    function toggleColor(){
      for (var i = 0; i < colors.length; i ++ ){
        colors[i].style.color = 'blue';
      }
      this.style.color = 'orange';
    }
    

    CSS

    p { 
     color: blue;
    }
    

    Check out this codepen.