There should be only one element with the given identifier. If you are stuck in this situation, see the second half of my answer for options.
How the browser works when you have several elements with the same identifier (illegal HTML) is not determined by the specification. You can check all browsers and find out how they behave, but it is unwise to use this configuration or rely on any specific behavior.
Use classes if you want multiple objects to have the same identifier.
<div> <span class="a">1</span> <span class="a">2</span> <span>3</span> </div> $(function() { var w = $("div"); console.log($(".a").length);
If you want to look reliably at elements with identifiers that are the same because you cannot fix the document, then you will have to do your own iteration, since you cannot rely on any of the built-in DOM functions.
You can do it as follows:
function findMultiID(id) { var results = []; var children = $("div").get(0).children; for (var i = 0; i < children.length; i++) { if (children[i].id == id) { results.push(children[i]); } } return(results); }
Or using jQuery:
$("div *").filter(function() {return(this.id == "a");});
JQuery working example: http://jsfiddle.net/jfriend00/XY2tX/ .
As for why you get different results, this is due to the internal implementation of any part of the code that performs the actual selection operation. In jQuery, you can examine the code to find out what a given version does, but since it is illegal HTML, there is no guarantee that it will remain unchanged over time. From what I saw in jQuery, it first checks to see if the selector is a simple id like #a , and if so, just use document.getElementById("a") . If the selector is more complex than the one, and querySelectorAll() exists, jQuery often passes the selector to a browser built-in function that will have an implementation specific to that browser. If querySelectorAll() does not exist, then it will use the Sizzle selection mechanism to manually find a selector that will have its own implementation. Thus, you can have at least three different implementations in the same browser family, depending on the exact selector and how the new browser is. Then, individual browsers will have their own querySelectorAll() implementations. If you want to deal with this situation reliably, you probably have to use your own iterative code, as shown above.
jfriend00 Dec 14 2018-11-11T00: 00Z
source share