Search code examples
htmljqueryidentifier

How does jQuery work when there are multiple elements with the same ID value?


I fetch data from Google's AdWords website which has multiple elements with the same id.

Could you please explain why the following 3 queries doesn't result with the same answer (2)?

Live Demo

HTML:

<div>
    <span id="a">1</span>
    <span id="a">2</span>
    <span>3</span>
</div>

JS:

$(function() {
    var w = $("div");
    console.log($("#a").length);            // 1 - Why?
    console.log($("body #a").length);       // 2
    console.log($("#a", w).length);         // 2
});

Solution

  • Having 2 elements with the same ID is not valid html according to the W3C specification.

    When your CSS selector only has an ID selector (and is not used on a specific context), jQuery uses the native document.getElementById method, which returns only the first element with that ID.

    However, in the other two instances, jQuery relies on the Sizzle selector engine (or querySelectorAll, if available), which apparently selects both elements. Results may vary on a per browser basis.

    However, you should never have two elements on the same page with the same ID. If you need it for your CSS, use a class instead.


    If you absolutely must select by duplicate ID, use an attribute selector:

    $('[id="a"]');
    

    Take a look at the fiddle: http://jsfiddle.net/P2j3f/2/

    Note: if possible, you should qualify that selector with a type selector, like this:

    $('span[id="a"]');
    

    The reason for this is because a type selector is much more efficient than an attribute selector. If you qualify your attribute selector with a type selector, jQuery will first use the type selector to find the elements of that type, and then only run the attribute selector on those elements. This is simply much more efficient.