I'm trying to access the html contents of an script block with the type set to "text/template". I've heard of template engines using such tags, but my application is very simple and loading an entire engine is unnecessary. Can someone shed some light on how I select that element? I think jQu开发者_开发百科ery's .html() function will get me the content but I can't seem to find the element.
The template looks like:
<script type="text/template" id="repeating-form-section-template">
<div class="repeating-form-section">
<label>Field Name:</field>
<input type="text" value="default value" name="field_name" />
</div>
</script>
Things I've tried:
getElementById('repeating-form-section-template');
$('script').filter(...);
$('#repeating-form-section-template');
$("script[type='text/template']");
Thanks!
Both:
$('#repeating-form-section-template');
$("script[type='text/template']");
Work fine. Make sure you check them after DOM load. Example: http://jsfiddle.net/niklasvh/VKqPX/
It should be this easy:
http://jsbin.com/evozi5/edit
For a preview: http://jsbin.com/evozi5/
The code tho is simply:
var someVar = $('#repeating-form-section-template').html();
$('#where-i-want-content').append(someVar);
Note
jQuery must be loaded before this will work tho. So:
<script src="jquery.js"></script>
<script> /* your code */ </script>
<script type="text/template"></script>
innerHTML
is generally considered a bad thing to use, but it's the perfect thing to use here:
var template = document.getElementById("repeating-form-section-template").innerHTML;
document.getElementById('where-you-want-the-content').innerHTML = template;
精彩评论