db2791 db2791 - 1 year ago 70
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">


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}}">

Answer Source

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
<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 id="div2" class="repeatedDiv">
    <button class="reply-button">div2</button>
<div id="div3" class="repeatedDiv">
    <button class="reply-button">div3</button>

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download