Javascript returns the same id for every iterated element in html

I have website which i build using Django where every visitor can leave their message or press a like button on any comment. I would like to show how many of a comment has been liked by the user. As each comment is unique, I think to access the comment_id attribute which I wrote in the html part. I then use a simple js function to retrieve the id. The problem is, although html is showing unique id for each comment, Javascript still return the same id, that is the id of the first comment that is written on the page. Can someone tell me where is my mistake in this case? Thank you in advance for your help.

my code in js: function likeButton(){ let el = document.getElementById("chat-icon-thumbsup") alert(el.attributes["comment_id"].value) };

my html code, which is looping the datatable records "comment" from a datatable in Django framework: {% for comment_ in comments %} <strong> {{ }} - {{ comment_.date_added }} <button><i comment_id="{{ comment_.comment_id }}" id="chat-icon-thumbsup" class="fa fa-fw fa-thumbs-up" title="like this comment" onclick="likeButton()"></i></button> {{ comment_.nr_of_likes }} <br/> </strong> {{ comment_.body }} <br/> {% endfor %}

image 1: here you see when I inspect the DOM elements, it retrieves different "comment_id" enter image description here image 2 and image 3: every button pressed in the comment line alerting the same id, which is 16 enter image description here enter image description here

I tried to google any possible same problem, but no solutions found

In HTML an ID should be unique on every page. JS will therefore only return the first field it finds with that ID. What you should be using is a class-name that defines your field, like this for example:

<i id="comment_{{ comment_.comment_id }}" class="fa fa-fw fa-thumbs-up chat-icon-thumbsup" ....>

Then you can use document.getElementsByClassName("chat-icon-thumbsup"), there is a reason why it's called getElementById as singular and not getElementsById

Back to Top