Mr. B
Mr. B

Reputation: 2787

Trying to open Modal window with click on classname instead of id

Hellow Everyone,

I believe I'm missing something very simple, but I can't seem to find it. I'm trying to open a modal window when the user clicks on a div. When the div has the "id" of myBtn1, it works. But when the div has the "class" of myBtn1, it doesn't work.

Any help is greatly appreciated.

This works

// Get the button that opens the modal
var btn = document.getElementById("myBtn1");

<a href="http://www.cnn.com/" target="_blank">
<div id="myBtn1">Open Cnn</div>
</a>

This doesn't work.

// Get the button that opens the modal
var btn = document.getElementsByClassName("myBtn1");

<a href="http://www.cnn.com/" target="_blank">
<div class="myBtn1">Open Cnn</div>
</a>

Upvotes: 1

Views: 1792

Answers (1)

Suren Srapyan
Suren Srapyan

Reputation: 68635

getElementsByClassName returns an array-like object. You need to get the first item from it via index.

If you notice, getElementById is in a single form, but getElementsByClassName is in the plural form

var btn = document.getElementsByClassName("myBtn1")[0];

<a href="http://www.cnn.com/" target="_blank">
   <div class="myBtn1">Open Cnn</div>
</a>

Upvotes: 3

Related Questions