Reputation: 2787
When I pass HTML elementals as strings in my object then they are not converted to elements upon rendering, so my template gets filled like this
<tr><td>"<img src="path/pic.png" />"</td></tr>
If I pass DOM elementals then I get
<tr><td>[Object HTMLImageElement]</td></tr>
How can I get the actual image rendered as a DOM element ?
Using jQuery Template plugin should help to greatly reduce the HTML string building usage.
Edit: Simple example below that grabs the DOM elements and then gives it to jquery template, which renders it.
source HTML
<div id="source-id"><a href="http://link/to/this.file" title="foo">bar</a> <img src="path/pic1.png" />pic1_text <img src="path/pic2.png" title="picture 2" />pic2_text</div>
<div id="target-id"><div>
jquery template
<script type="text/x-jquery-tmpl" id="linkTemplate"><table><tr><td>${link}</td><td>${img}</td></tr></table></script>
jquery
var data = {
'link': '',
'img': ''
};
var source_data = $('#source-id');
data.link = $(source_data).find('a').eq(0).clone()[0];
data.img = $(source_data).find('img').eq(1).clone()[0];
$('#target-id').html($('#linkTemplate').tmpl(data));
Output
<table><td>http://link/to/this.file</td><td>[object HTMLImageElement]</td></table>
As you can see is the AnchorElement () broken and image is not displayed.
JS fiddle example
Upvotes: 1
Views: 5478
Reputation: 111365
So basically the problem is how to get underlying HTML from a DOM element. You can use outerHTML
property for this:
data.img = $(source_data).find('img').eq(1).clone()[0].outerHTML;
which should return <img src="path/pic2.png" title="picture 2" />
as a string.
UPDATE JQuery templating engine automatically escapes values before displaying, to display raw html without escaping you need to modify your templates:
<script type="text/x-jquery-tmpl" id="linkTemplate">
<table><tr>
<td>{{html link}}</td>
<td>{{html img}}</td>
</tr></table>
</script>
(outerHTML
is still needed)
Upvotes: 3
Reputation: 1027
Here's an example of some working code:
<td class="test"></td>
<script>
$('.test').append('<img src="path/pic.png">');
</script>
Upvotes: -2