Reputation: 2787
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
Reputation: 68635
getElementsByClassName
returns an array-like object
. You need to get the first item from it via index
.
If you notice, getElement
ById is in a single form, but getElements
ByClassName 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