johnny 5 johnny 5 - 11 months ago 33
jQuery Question

jQuery How To Modify html of a cloned element in memory

I'm trying to modify the html of a template in memory and then prepend it to another html element

var messageTemplate = $("#messageTemplate").clone()
var timeStamp = message.TimeStamp;
var relativeTime = moment(timeStamp, "YYYYMMDD").fromNow();



Grabing the template works fine and prepending it however, the html is the original template, and is unmodified even though I'm setting the html. Can anyone explain how to properly set the html of a cloned element?

I've created a fiddle here


Edit, Updated

jQuery was not loaded at jsfiddle. Note also that you were previously prepending duplicate ids to document; id in document should be unique. Redefine variable template when setting unique id, new html at element. The same process can be used if multiple elements are initially contained within template html string variable; that is use .filter(), create unique id for element, define or redefine each variable name which references a cloned element

var template = $("#template")


// re-define `template`
template = $(template).filter("#username")
           .attr("id", "username-" + $("[id^=username]").length)
           .html("new user");



  background-color: blue;
<script src=""></script>
<div id="template" class="hidden">
<span id="username">Test User</span>

<div id="container">
<span>Element container</span>


messageTemplate appears to return .html() of #messageTemplate element, that is child element .outerHTML, not #messageTemplate element.

Try substituting .filter() for .find() to filter child element siblings of #messageTemplate contained in messageTemplate jQuery object.