db2791 db2791 - 1 month ago 4
HTML Question

Is it bad practice to hold information in the id of an HTML element?

Let's say I have a template and I want to loop and create div's. I want to listen to clicks on the buttons contained in each of these divs:

<div class="repeatedDiv">
<button class="reply-button">
</div>

$('.reply-button').on('click',function(e)...)


I want to make the reply button function specific to the div that it was selected on. Would it be bad to have something like:

<div class="repeatedDiv">
<button class="reply-button" id="reply-{{this.id}}">
</div>

Answer

Don't make it more complicated than it really is

$(document).on('click', '.reply-button', function(e){
  var divClicked = $(e.target).closest('.repeatedDiv');
  // do something with clicked div
  // var divClicked is the div elmt that contains the button that was clicked
  // doing it this way you might not even need an id at all
  console.log(divClicked.attr('id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1" class="repeatedDiv">
    <button class="reply-button">div1</button>
</div>
<div id="div2" class="repeatedDiv">
    <button class="reply-button">div2</button>
</div>
<div id="div3" class="repeatedDiv">
    <button class="reply-button">div3</button>
</div>

And if you do need an id when creating a new div create it dynamically with e.g.

var newID = "id-" + Date.now();
console.log(newID);