vicsz
vicsz

Reputation: 9744

Jquery - appending a HTML5 template while setting an attriibute?

Is there any easy way to add an HTML 5 template to the body, and at the same time update an attribute? .. In my case I'm trying to update the id attr. The intended output would be to NOT update the id of #myTemplate, but my I add the template to have the div id set to something specific.

<body>
<template id='myTemplate'>
   <div>My Div Example </div>
</template>

<script>
   $(function(){
       $("body").append($('#myTemplate').html());
   });
</script>
</body>

---> Intended addition after the script runs (in body):

<div id="someNewId">My Div Example</div>

Upvotes: 0

Views: 73

Answers (2)

Volune
Volune

Reputation: 4339

Put it in a jQuery object, edit all the attributes you want, then append it to the body:

var html = $('#myTemplate').html(); //or any other way to generate html
var $newContent = $(html);
$newContent.filter('div').attr('id','someNewId');
$('body').append($newContent);

Upvotes: 1

GillesC
GillesC

Reputation: 10874

This should do the trick, if you want to go down the html() way, and will actually wrap the content inside a div as your current code will just input the content of template inside the body but without the wrapping div.

$(function(){
    $("body").append($("<div id='myNewId'>").html($('#myTemplate').html()));
});

Upvotes: 1

Related Questions