John B.
John B.

Reputation: 2359

Set ID on currently appended element

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/

Upvotes: 2

Views: 5936

Answers (3)

The Alpha
The Alpha

Reputation: 146201

You can use find('div:first')

$('#output').append($('#element-template').html())
.find('div:first').attr('id', 'my-element');​

Example.

Upvotes: 2

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196026

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/

Upvotes: 5

PhearOfRayne
PhearOfRayne

Reputation: 5050

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/

Upvotes: 3

Related Questions