2

I am creating buttons in jQuery dynamically. I need to add data attributes:

So I saw the answer here: Dynamically create buttons with Jquery

$(document).ready(function() {
  for(i = 1; i <=10; i++) {
     $('<button/>', {
        text: i, //set text 1 to 10
        id: 'btn_'+i,
        click: function () { alert('hi'); }
    });
  }
});

I am adding the data-attributes like this:

$(document).ready(function() {
  for(i = 1; i <=10; i++) {

   $('<button/>', {
        text: i, //set text 1 to 10
        id: 'btn_'+i,
        click: function () { alert('hi'); }
    }).attr('data-test', 1).attr('data-test2', 2);

  }
});

I was thinking that if I could do something similar to the way we add text and id attributes

1 Answer 1

7

You can do that, but since the key contains - you need to pass the key as a string literal like

$(document).ready(function() {
  for (i = 1; i <= 10; i++) {

    $('<button/>', {
      text: i, //set text 1 to 10
      id: 'btn_' + i,
      click: function() {
        alert('hi: ' + $(this).attr('data-test'));
      },
      'data-test': 1
    }).appendTo('body');

  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Sign up to request clarification or add additional context in comments.

1 Comment

I know that this an older topic but I found this helpful and it will help others as it is the first link in google searches... You can do the same with regular attributes too...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.