By Sam Deering

jQuery bind() elements with same id

By Sam Deering

OK, somehow you’ve managed to get into a situation where you need to bind to elements of the same id. Now, if you can you should add a class to each element and bind to that!

Note: You should only use the live() function on elements that have been introduced dynamically within the page, otherwise use the bind() function.

This little function find elements with duplicate ids.

(function(document, $){
    // little debug helper script to notify us when the
    // dom is updated with a contains duplicate ID'd elements
    $(document).bind('DOMNodeInserted', function (event) {

        var duplicateDomElements = [];

        $('[id]').map(function () {
            var ids = $('[id=' + + ']');
            if (ids.length > 1 && ids[0] == this) {

        if (duplicateDomElements.length > 0) {
            alert('Recent action duplicated a dom element ID with name(s) [' + duplicateDomElements + ']');

})(document, jQuery);

Note: using div#id will soemtimes produce a slower result than just #id so be careful how many preceding tags you put on your selectors. Also as a tip, if the two classes are calling the same function then you can add the selectors together like this:

$('.clickButton1, .clickButton2').bind('click', function() {
	//your code

//instead of 

$('.clickButton1').bind('click', function() {
	//your code

$('.clickButton2').bind('click', function() {
	//your code

Stopping Action on Duplicate Elements

A fix to stop further actions on duplicate elements is to use both prevent default and stop propagation which will stop the default action and any immediate actions for elements with the same id. Like so:


Further Problems: assigning classes to elements with the same id

.each is applying the class tag to the first element with that id

0 [object HTMLDivElement]
0 [object HTMLDivElement]

If you apply “div” to the jQuery selector it seems to work.

$('div#searchResultsContainer').each(function(index, value)
    // $(this).addClass('SSP'+index);

Also see: jquery binding to created elements

The most important and interesting stories in tech. Straight to your inbox, daily. Get Versioning.
Login or Create Account to Comment
Login Create Account