Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't fire click event on the elements with same id

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!:)

like image 638
Dmitry Belaventsev Avatar asked Oct 02 '11 14:10

Dmitry Belaventsev


People also ask

How do I select all elements with the same ID?

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.

How do you add an event listener to multiple elements with the same ID?

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.

Does Onclick work with all elements?

All HTML elements can have an onclick attribute.


1 Answers

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.

like image 167
Jared Farrish Avatar answered Sep 18 '22 16:09

Jared Farrish