Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set ID on currently appended element

Tags:

jquery

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/

like image 881
John B. Avatar asked Dec 03 '25 17:12

John B.


2 Answers

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/

like image 112
Gabriele Petrioli Avatar answered Dec 06 '25 08:12

Gabriele Petrioli


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/

like image 33
PhearOfRayne Avatar answered Dec 06 '25 09:12

PhearOfRayne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!