I have a <script type="text/template> which inner HTML I use to create new elements.
How can I additionally add an ID to those created elements?
<script type="text/template" id="element-template">
<div class="element-container">
<p>Template</p>
</div>
</script>
Desired outcome:
<div id="my-element" class="element-container">
<p>Template</p>
</div>
Following code works, but I don't want to use find('.element-container') on the parent because the class could change in the future:
var template = $('#element-template').html();
$('#output').append(template).parent().find('.element-container').attr('id', 'my-element');
Use can find a JSFiddle here: http://jsfiddle.net/RZrkB/1/
I would make the template variable hold a jquery object instead of the html.
That way you can .clone() it and directly add an id on it.
var template = $( $('#element-template').html() );
$('#output').append( template.clone().attr('id','my-element') );
Demo at http://jsfiddle.net/gaby/RZrkB/3/
If you just need to set the id attribute for the first child element you could do it using jQuery .children() like this:
var template = $('#element-template').html();
var $output = $('#output');
$output.append(template).children(':first').attr('id', 'my-element');
Example: http://jsfiddle.net/fewds/RZrkB/4/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With