Search code examples
javascriptbuttonstylesgetelementbyid

Using a <button> and getElementsByClassName () to change the color of all the <p> in my document


I'm trying to use a with js script on HTML to change the color of all the paragraphs in my document.

So far I have used: <button type="button" onclick="document.getElementsByClassName('paragraph').style.color='white'">white Font all</button>

and also

<button type="button" onclick="document.getElementsByTagName('p').style.color='white'">white Font all</button>

but it doesn't seem to work. I want to change the color of all the paragraph fonts in my document to white, or any color. I used ID and it works fine for 1 paragraph, but I need all of them at the same time.

<button type="button" onclick="document.getElementsById('intro').style.color='white'">white Font Intro</button>

Thanks for any help!


Solution

  • The issue is that ClassName and TagName return a collection of elements rather than a single element. You must loop through the collection to change the style of all elements.

    <button type="button" onclick="changeColor('white')">White Font All</button>
    
    <script>
      function changeColor(color) {
        const elements = document.getElementsByTagName('p');
        for (let i = 0; i < elements.length; i++) {
          elements[i].style.color = color;
        }
      }
    </script>