<!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’?
Explanation for jQuery
Also, in your case, jQuery should select only one element, and the first element for
ID. Since you have also givendiv, it usesgetElementsByTagName, 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
idattribute 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