JavaScript
Article
By Sam Deering

Attaching Events to Elements of the Same ID

By Sam Deering
Last chance to win! You'll get a... FREE 6-Month Subscription to SitePoint Premium Plus you'll go in the draw to WIN a new Macbook SitePoint 2017 Survey Yes, let's Do this It only takes 5 min

OK so we’ve all ran into this problem for some reason or another – 2 elements with the same id.

Basically, you shouldn’t have elements on the same page with the same id, it’s bad programming! If however, you do find yourself in this situation (ie. your trying to fix or extend someone else’s code). You can add different class names to the elements and use the $(‘.elementclass’).attr($(this).src) command to determine which element you have chosen.

If you want to reference elements together then you can simply add them to the same class and select them this way (using a full stop instead of a hash).

--ADVERTISEMENT--

2 elements with same id example

$('.elementclass').attr($(this).src);
Login or Create Account to Comment
Login Create Account
Recommended
Sponsors
Get the most important and interesting stories in tech. Straight to your inbox, daily.Is it good?