[Answer]-JQuery grabs only the first element in html (in a Django app)

1👍

So as I mentioned in the comments, you need to modify your HTML first to change the IDs to a class … something like this:

{% for c in comments %}     
    <div class="col-md-3 pull-right">
    {{c.commenter}} Wrote: 
    &nbsp; <span class="grey"> {{c.pub_date|naturaltime}} </span>
    </div>
    <br>

    <div class="col-md-1">
        <i class="glyphicon glyphicon-heart" id="likecomment" name="{{c.id}}" value="{{c.id}}" title="Like it">
        {{c.likes}}
      </i>&nbsp;
        <i class="likecomment"> </i>
    </div>

    <div class="col-md-11">
           {{c.body}}  
    </div>

     <br> 
    <hr>

{% endfor %}

And then modify your jQuery to access that class, like this:

function likeSuccess(data, textStatus, jqXHR){     
    $('.likecomment').html(data);
     alert(cid);
}

Voila! The key here is that this isn’t a jQuery thing … its an HTML thing. When an ID is assigned to an element, it must be unique. Trust me, you violate that rule, and you’ll get much more wacky behavior than just jQuery only working on the first one.

Leave a comment