2

I have this in my HTML:

<script id="tpl" type="text/template">
  <div data-id="" class="line">
    ...
  </div>
</script>

In JS I'm getting that template to add it into the HTML, then set each a data attribute, as:

$('.add-line').on('click', function(){
      var tpl = $('#tpl').html()
      $(tpl).data('id', 'TEST')
      $(tpl).attr('data-id', 'TEST')
      $('.target').append(tpl)
})

But none of these added have any data-id. What am I doing wrong?

Ignacio
  • 7,947
  • 15
  • 63
  • 74

1 Answers1

2

Try this

$('.add-line').on('click', function() {
  var tpl = $($('#tpl').html()).map(function() {
    if ($(this).hasClass('line')) {
      $(this).attr('data-id', 'TEST');
    }

    return this;
  });

  $('.target').append(tpl);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script id="tpl" type="text/template">
  <div data-id="" class="line">Test</div>
</script>

<a class="add-line">Add line</a>
<div class="target"></div>

Or more shorter version with temporary div

$('.add-line').on('click', function(){
  var content = $('#tpl').html(),
      tpl = $('<div />').html(content).find('.line').attr('data-id', 'TEST');
      
  $('.target').append(tpl);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script id="tpl" type="text/template">
  <div data-id="" class="line">Test</div>
</script>

<a class="add-line">Add line</a>
<div class="target"></div>
Oleksandr T.
  • 76,493
  • 17
  • 173
  • 144