Franco Trucco Franco Trucco - 1 month ago 10
HTML Question

How to count the quantity of items in Unordered List. JQuery

I'm new to the StackOverflow community!
I've been searching for this topic and in some of them said that I can know what I'm looking for with .length but I cannot make it happen.

I'm also new in JQuery and JS, if anything in my code is messy I apologize.

My code:

$('#btnComments').click(function () {
if ($('#commentArea').val() != "") {
var $newli = document.createElement('li');
$newli.textContent = $('#commentArea').val();
$('#listaDeComentarios').after($newli);
$('#commentArea').val('');
var cantLiEnUl = $('#listaDeComentarios').length;
$newli.tagName = 'Comments[' + cantLiEnUl.toString() + ']';
}
});


In the first part of my code I'm just getting the text from a TextArea and add it to a Comment List. What I'm trying to do is to set the proper index to the name of the li because I'm posting that list with a model, and if I don't give each li an index then this property in the model reaches with null value.

I've been doing some console.log(cantLiEnUl) to know how was changing the value and it didn't, it always was 1. #listaDeComentarios is the id of my ul.

If anything isn't clear enough I'll be trying to explain myself better.

Thanks in advance!

I've found after I read the comment about @Turnip.

I'm posting it because he replied to a comment and cannot mark it as the solution. My problem was the .after

You should be using .append instead of .after else the length will always be zero. You aren't actually adding the li to the ul. Also, you can't assign value to tagName - this is the 'type' of the element. In your case $newli.tagName equals 'LI'

Thanks!

Answer

I'm going to take a wild guess and assume that you are trying to do something like this:

$('#btnComments').click(function () {
    if ($('#commentArea').val() != "") {
        var $newli = document.createElement('li');
        $newli.textContent = $('#commentArea').val();

        /**
        * Use `.append` not `.after`...
        */
        $('#listaDeComentarios').append($newli);
        $('#commentArea').val('');
      
        /**
        * Check the length of the `li` not the `ul`...
        */
        var cantLiEnUl = $('#listaDeComentarios li').length;
        
        /**
        * Replace 'data-myData' with whatever attribute you are wanting to set...
        */
        $($newli).attr('data-myData', 'Comments[' + cantLiEnUl.toString() + ']');
    }
});
#listaDeComentarios li:after {
  content: ' - ' attr(data-myData);
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<textarea id="commentArea" placeholder="Enter some text..."></textarea>
<br>
<button id="btnComments">
Click
</button>

<ul id="listaDeComentarios">

</ul>