-1

Is it possible to use a JavaScript document.getElementsByClassName variable in an if statement with event.target?

I want to achieve something like this:

var signInModals = document.getElementsByClassName("signInModal");

if (event.target == signInModals) {
        alert("It worked!");
}

Thank you!

Combobulated
  • 148
  • 2
  • 13

2 Answers2

5

You are trying to compare an HTML collection to an element. That is never going to work. You would need to loop over the HTML Collection and check each one.

Seems like you are trying to see if an element has a class so just check for the class.

if(evt.target.classList.contains("signInModal"))

other option is to check to see if it is a parent (depending on what evt is)

if(evt.target.closest(".signInModal"))
epascarello
  • 204,599
  • 20
  • 195
  • 236
0

Well, event is a reference to the Object itself, not its value. So you are saying is this Object that is clicked this Object that I got from the class name. The answer will always be false. So to answer your question yes it is, but it does not make sense to do that, you probably want to check if a property matches.

For example: when this button is clicked change the button color to the same color has this Html object, and then you can use the if statement to say if (button color == html object color) alert("It worked")

JimiA
  • 91
  • 4