Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

count div elements with the same id JQUERY

Tags:

html

jquery

css

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.

like image 718
leeshin Avatar asked Nov 11 '13 04:11

leeshin


People also ask

Can 2 divs have same ID?

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.

What happens if two elements have the same ID?

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.

Can two elements share the same ID?

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.

How do I find an element with a specific ID?

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.


2 Answers

Give class name for div and paste the below code.. It will give the count.

var conveniancecount = $("div[class*='conveniancecount']").length;
like image 195
Sasidharan Avatar answered Oct 13 '22 18:10

Sasidharan


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

like image 24
Sachin Avatar answered Oct 13 '22 19:10

Sachin