0

I am trying to add an onClick event to the buttons I created here: https://makerlist.io/smart-feature-finder/. I am adding a "Hello, World!" statement that appears when the button is clicked to test it. Here is the code I'm using, however nothing appears. Any ideas on what I am missing?

document.getElementsByClassName(".esg-filterbutton").addEventListener("click", myFunction);

function myFunction() {
    alert ("Hello, World!");
}

Thanks,

Jonahan

2 Answers 2

1

Your selector returns an array-like object known as a HTMLCollection not a single element.

Try,

document.getElementsByClassName("esg-filterbutton")[0].addEventListener("click", myFunction);

Notice I'm grabbing the first element in the array?

Also I removed the . before the name of the class. As you are specifying that you want to select a class in the function, you don't need to put a ..

Sign up to request clarification or add additional context in comments.

4 Comments

Technically it is not an array, it is a live HTMLCollection.
@epascarello It is an array-like object. Array is merely my way of explaining it in layman's terms. Thanks for the link though.
Works! Thanks @Script47.
But what if I want to assign a function to all elements of the class, not just the first one? How do I do that?
0

You can bind a click event to the element with class esg-filterbutton if you wish to apply the event to all your buttons.

$('.esg-filterbutton').click(function()
{
    alert ("Hello, World!");
});

Here's an example : https://jsfiddle.net/DinoMyte/Lb1wj47j/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.