Could you help me to understand - where I made the mistake. I have the following html code:
<div id="container">
<a href="#info-mail.ru" id="getInfo" onClick="return false;">Info mail.ru</a>
</div>
<div id="container">
<a href="#info-mail.com" id="getInfo" onClick="return false;">Info mail.com</a>
</div>
<div id="container">
<a href="#info-mail.net" id="getInfo" onClick="return false;">Info mail.net</a>
</div>
and the following js code (using jQuery):
$('#getInfo').click(function(){
alert('test!');
});
example here
"Click" event fired only on first link element. But not on others.
I know that each ID in html page should be used only one time (but CLASS can be used a lot of times) - but it only should (not must) as I know. Is it the root of my problem?
TIA!
upd: Big thx to all for explanation!:)
Use the querySelectorAll() method to select elements by multiple ids, e.g. document. querySelectorAll('#box1, #box2, #box3') . The method takes a string containing one or more selectors as a parameter and returns a collection of the matching elements.
Adding event listener to multiple elements To add the event listener to the multiple elements, first we need to access the multiple elements with the same class name or id using document. querySelectorAll() method then we need to loop through each element using the forEach() method and add an event listener to it.
All HTML elements can have an onclick attribute.
Use a class for this (and return false
in your handler, not inline):
<div id="container">
<a href="#info-mail.ru" class="getInfo">Info mail.ru</a>
</div>
<div id="container">
<a href="#info-mail.com" class="getInfo">Info mail.com</a>
</div>
<div id="container">
<a href="#info-mail.net" class="getInfo">Info mail.net</a>
</div>
$('.getInfo').click(function(){
alert('test!');
return false;
});
http://jsfiddle.net/Xde7K/2/
The reason you're having this problem is that elements are retrieved by ID
using document.getElementById()
, which can only return one element. So you only get one, whichever the browser decides to give you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With