Reputation: 9744
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
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
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