0

apologies in advance if this seems super basic.

I'm confused as to why this works:

<div id="box">Hello World</div>
<button id="myButton">Click</button>

<script>
    let myBox = document.getElementById('box');
    let myButton = document.getElementById('myButton');

    myFunction = () => {                        
        myBox.innerHTML = 'Thanks';  
    }

    myButton.addEventListener("click", myFunction);
</script>

But this does not:

<div class="box">Hello World</div>
<button class="myButton">Click</button>

<script>
    let myBox = document.getElementsByClassName('box');
    let myButton = document.getElementsByClassName('myButton');

    myFunction = () => {                        
        myBox.innerHTML = 'Thanks';  
    }

    myButton.addEventListener("click", myFunction);
</script>

The second, which gets the DOM element by class name rather than Id generates the following error in the console:

Uncaught TypeError: myButton.addEventListener is not a function

Had searched around but cant seem to find any clear answer.

Thanks!

juanferrer
  • 1,192
  • 1
  • 16
  • 29
  • Use `window.querySelector` if you need to select a single element by a class – MinusFour Aug 02 '17 at 15:59
  • The function's name already contains a hint: getElement**s**ByClassName returns a HTMLCollection, something similar to an array of elements. That is because you can have only one element with a specific id, but multiple elements with the same class name. If you are sure that there is one and only one element with the given class name, you could simply use `document.getElementsByClassName('box')[0]`. Otherwise you have to find which of your boxes belongs to the clicked button. – Stephan Aug 02 '17 at 16:06
  • Thanks Stephan. This makes total sense. – Alex Herrera Aug 02 '17 at 16:15

2 Answers2

3

document.getElementsByClassName returns multiple elements with the provided class name whereas getElementById returns single element with provided id.

Try:

let myButton = document.getElementsByClassName('myButton')[0]; // if there is single such button
Vaibhav Nigam
  • 1,334
  • 12
  • 21
1

Change your code to this as getElementsByClassName return a list of all elements with the specified class.

Hello World
        <button class="myButton">Click</button>

        <script>
            let myBox = document.getElementsByClassName('box')[0];
            let myButton = document.getElementsByClassName('myButton')[0];

            myFunction = () => {                        
                myBox.innerHTML = 'Thanks';  
            }

            myButton.addEventListener("click", myFunction);
        </script>
Sam TNT
  • 11
  • 2