Refer to attached screenshot, the div with id ‘item’ were added by
$("#items").prepend(template);
where template is the html of each div with id ‘item’, if I get $(‘#item’).length but it always return 1, does anyone know why? How can I get the correct number of item?
var num = $('#item').length;
alert(num);
2
Answers
Use
class
attribute instead ofid
attribute sinceid
attribute should be unique within the page. A sample of it would look like:You are appending a new element with
id = "item"
to another element withid = "items"
, so what you actually need is the number of children inside#items
:In any case, as @mandy8055 has pointed out, you are creating multiple items with duplicate ids (
#item
). You can easily fix that using a class instead, so the following would work: