johnny 5 johnny 5 - 5 months ago 11
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()
.removeAttr('id').removeClass("hidden").html();
var timeStamp = message.TimeStamp;
console.log(timeStamp)
var relativeTime = moment(timeStamp, "YYYYMMDD").fromNow();

$(messageTemplate).find("#message").html(message.Data)
$(messageTemplate).find("#moment").html(relativeTime);
$(messageTemplate).find("#senderName").html(message.SenderUser.Username);

$("#message-dropdown").prepend(messageTemplate);


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 https://jsfiddle.net/d9s6twp1/5/

Answer

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")
              .clone().removeAttr("id")
              .removeClass("hidden")
              .html();

console.log(template);

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

console.log(template[0].outerHTML);

$("#container").prepend(template)
.hidden{
  display:none;
}

#container{
  background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="template" class="hidden">
<span id="username">Test User</span>
</div>

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

jsfiddle https://jsfiddle.net/d9s6twp1/7/


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.