jQuery bind() elements with same id

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=' + this.id + ']');
            if (ids.length > 1 && ids[0] == this) {
                duplicateDomElements.push(this.id);
            }
        });

        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:

e.preventDefault();
e.stopImmediatePropagation();

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]
SSP0
0 [object HTMLDivElement]
SSP0

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

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

Also see: jquery binding to created elements

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

No Reader comments

Comments on this post are closed.