skip to Main Content

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);

enter image description here

2

Answers


  1. Use class attribute instead of id attribute since id attribute should be unique within the page. A sample of it would look like:

    $(document).ready(function() {
      $("#addItem").click(function() {
        var template = '<div class="item">Item</div>';
        $("#items").prepend(template);
        var num = $(".item").length; // <--- notice here
        alert(num);
      });
    });
    <div id="items"></div>
    <button id="addItem">Add Item</button>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    Login or Signup to reply.
  2. You are appending a new element with id = "item" to another element with id = "items", so what you actually need is the number of children inside #items:

    $("#items").children().length;
    

    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:

    $(".item").length
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search