Harald
Harald

Reputation: 1037

Manipulate parts of html with jquery

In my html I have a (hidden) template, something like

<div class="tabletemplate dontshow" >
   <p class="movieFile"></p>
   <p class="movieDirector"></p>
</div>

I obtain the template by

var tableTemplate = $(".tabletemplate").clone().removeClass("dontshow");

I then want to insert text strings into the template. I tried a few things like

tableTemplate.find(".movieFile").text(movieInfo.FileName);

or

$(".movieFile", tableTemplate).text(movieInfo.FileName);

but none seem to work.

How can I do that easily, ideally without having to learn an entire new js library.

Upvotes: 1

Views: 71

Answers (3)

Michal Olszowski
Michal Olszowski

Reputation: 805

The best solution for that is function appendTo:

$(".movieFile").appendTo(movieInfo.FileName);
or

tableTemplate.find(".movieFile").appendTo(movieInfo.FileName);

Upvotes: 1

Harald
Harald

Reputation: 1037

It seems I had it right all along, except that my movieInfo.FileName object doesn't work for some reason, although firebug shows me the correct string. I have to work on that some more. Replacing it with text constants showed me that I was on the right track... It turned out I didn't need "append" or "appendTo".

Here's what I have and it works:

    jQuery.fn.outerHTML = function () {
        return (this[0]) ? this[0].outerHTML : '';
    };

    function createTableElement(movieInfo) {
        var template = tableTemplate.clone();

        // template.find(".movieFile").text(movieInfo.FileName);
        template.find(".movieFile").text("the movie");
        template.find(".movieDirector").text("the director");
        return template.outerHTML();
    }

This function returns the html string of the entire div which I then can use to construct my table

Thank you all for your help and the very quick responses!

Upvotes: 0

RTB
RTB

Reputation: 5823

Try this:

$(".tabletemplate").clone().removeClass("dontshow").appendTo(".tabletemplate");
var movieFile = $(".tabletemplate").find(".movieFile")[0];
$(movieFile).text(movieInfo.FileName);

Works for me. You would have to change the last appendTo class to the parent of tabletemplate ofcourse.

Upvotes: 1

Related Questions