简体   繁体   中英

Can we add attribute(i.e. id/class) on any div which is inside the <script type=“text/template” id=“template”><script>

I want to add the class attribute on #new-post which is content of <script type="text/template" id="template"></script>

Below is my code which is able to find the content of 'template' but not able to add the class attribute.

$('#template').contents().find('#new-post').addClass('hello');

HTML

<script type="text/template" id="template">
   <div id="new-post">
   &nbsp;
   </div>
</script>

A script element contains CDATA, it cannot have child elements ( < does not mean "start of tag" inside it (except when that tag is </script> )).

If you want to perform DOM manipulation of the contents of your template, then you must first parse the template into a DOM.

var template = $('#template').text(); 
var $template = $(template);
$template.addClass('hello');
alert($template.wrap('<div></div>').parent().html());

Why don't you render the template to the dom and then add the class.

Edit: Please note that your code doesn't work even if the div is inside a normal html tag.

Please refer this fiddle: http://jsfiddle.net/shyamchandranmec/R7g3S/

$('#foo').contents().find('#bar').addClass('fb');
$("#foo").find("#bar").addClass('foobar');

<div id="foo">
    <div id="bar">foo bar</div>
</div>

The class fb wont be added to the div #bar.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM