Home > OS >  html() is not populating HTML template
html() is not populating HTML template

Time:12-15

This is driving me crazy. Can anyone see what I'm doing wrong?

Here's my HTML template.

<template id="note-template">
    <div >
    </div>
    <div >
        <div >
            <div>
                <span ></span>
                &bull;
                <span ></span>
            </div>
            <div>
                <img  src="~/images/tteditnote.png" title="Edit Note">
                <img  src="~/images/ttdeletenote.png" title="Delete Note">
            </div>
        </div>
    </div>
</template>

And here's my JavaScript.

var $container = $('#trip-notes');
var $template = $('#note-template');
$container.empty();
response.forEach(function (element) {
    var $note = $($template.html());
    $note.find('.trip-note').html(element.html);
    $note.find('.note-author').text(element.author);
    $note.find('.note-date').text(element.createDate);
    $container.append($note);
});

Everything works exactly as expected except that my div.trip-note does not get set to the value in element.html.

author and createDate are set just fine. I've confirmed element.html contains the expected markup. I've retyped the class name several times (both in markup and in JavaScript). I tried mixing and matching html() and text() and the result is always the same: All elements are populated except for div.trip-note.

I'm either missing something very stupid or there is a peculiar issue going on.

Update

I've created a jsfiddle.

CodePudding user response:

.find() searches for descendants, it won't find the top-level element that you're searching from. Since .trip-note is one of the top-level elements of $note, it's note selected.

Instead of using $template.html(), make a clone of $template. Then everything will be a descendant. You can use .html() when you're appending to $container to exclude the <template> top-level element.

var $container = $('#trip-notes');
var $template = $('#note-template');
$container.empty();
response.forEach(function (element) {
    var $note = $template.clone();
    $note.find('.trip-note').html(element.html);
    $note.find('.note-author').text(element.author);
    $note.find('.note-date').text(element.createDate);
    $container.append($note.html());
});

  • Related