I created a more than one DIV with the same ID. I want to keep track of the number of DIV's by using JQUERY. This one does not seem to work.
var divid = "123456";
var count_id_len = $("#parentdiv").find("#"+divid).length;
console.log(count_id_len);
The result is always 1 even though there is more than one of them.
The HTML id attribute is used to specify a unique id for an HTML element. You cannot have more than one element with the same id in an HTML document.
The id must be unique. There can be only one element in the document with the given id . If there are multiple elements with the same id , then the behavior of methods that use it is unpredictable, e.g. document. getElementById may return any of such elements at random.
As the name suggests, ID is an identifier for the element in the whole document. So no two elements in a document can have the same id. If we try to give a same id to two different elements in a document, we would get a warning. The id in HTML5 should not contain any whitespaces.
Document.getElementById() The Document method getElementById() returns an Element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly.
Give class name for div and paste the below code.. It will give the count.
var conveniancecount = $("div[class*='conveniancecount']").length;
Having same id multiple times is not recommended by W3C. See what they say about it.
The id attribute specifies a unique id for an HTML element (the id attribute value must be unique within the HTML document). The id attribute can be used to point to a style in a style sheet. The id attribute can also be used by a JavaScript (via the HTML DOM) to make changes to the HTML element with the specific id.
Suggestion:
Use class name for all the divs you want to group and use this selector:
$('.myClassName')
See these references for more:
1. Why do Ids need to be unique
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With