$(“#id”) only selects the first element but $(“div

2019-02-19 18:30发布

问题:

<!DOCTYPE HTML>

<script src='http://code.jquery.com/jquery-latest.min.js'></script>

<body>

<div id='mydiv'>Hello, buddy.</div>
<div id='mydiv'>Hello, friend.</div>

</body>

When in JQuery, if I $('#mydiv') it will select only the first div, BUT if I do $('div#mydiv') it will select all of them.

I understand that specifying the element as well as the id, it will prevent from selecting other elements that have the same id but are not divs.

Isn't this a bug? Shouldn't $('#mydiv') select all elements which id is 'mydiv'?

回答1:

Explanation for jQuery

Also, in your case, jQuery should select only one element, and the first element for ID. Since you have also given div, it uses getElementsByTagName, and matches the attribute with ID. So, it returns all the instances. Please correct me if I am wrong.

Suggestion

According to web standards, the id attribute must be unique. So, each element should have unique ID. If you want to use things for multiple elements, you have classes.

Also, your HTML won't validate, if you have multiple IDs.

Also, from the XHTML 1.0 Spec

In XML, fragment identifiers are of type ID, and there can only be a single attribute of type ID per element. Therefore, in XHTML 1.0 the id attribute is defined to be of type ID. In order to ensure that XHTML 1.0 documents are well-structured XML documents, XHTML 1.0 documents MUST use the id attribute when defining fragment identifiers on the elements listed above. See the HTML Compatibility Guidelines for information on ensuring such anchors are backward compatible when serving XHTML documents as media type text/html.



回答2:

It's not a bug at all... IDs (#myId) are not supposed to be used in multiple instances. That's why we have classes (.myClasses).

So, you can use classes as much as you want. But IDs are always unique for each HTML page. You may have one ID showing up in many different pages, but always as a unique ID.



回答3:

#mydiv is likely optimized to use getElementById, which is described in the specs as:

Behavior is not defined if more than one element has this id.

Usually the first element with such an ID is returned though.