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?

1 Answer 1

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>

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

Comments

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.