I have a piece of html template in a string which I need to update. Say:
var tpl = "<div><a href="#"><img src="..."></a></div>";
How do I add a class to the a
tag and return back the updated string? This string template can be entirely customized so the code must not rely on this particular string.
If I do: $(tpl).find('a').addClass('myClass')
then the original tpl
variable will not be affected.
If I do: tpl = $(tpl).find('a').addClass('myClass').html()
then I will only get the contents of a
tag.
So what would be the correct approach?
The contents of tpl
should in the end be:
<div><a href="#" class="myClass"><img src="..."></a></div>
You can use $.fn.end() to return original matched set:
tpl = $(tpl).find('a').addClass('myClass').end().prop('outerHTML');
var tpl = '<div><a href="#"><img src="..."></a></div>'; tpl = $(tpl).find('a').addClass('myClass').end().prop('outerHTML'); console.log(tpl);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
And if you want to return the parent jq object, not the outer HTML string, remove prop()
:
tpl = $(tpl).find('a').addClass('myClass').end();
You can wrap your template around a div and go back to it after your modifications.
$(function() { var tmpl = '<div><a href="#"><img src="#"></a></div>'; tmpl = jQuery("<div class=\\"outer\\">") .append(tmpl) .find('a') .addClass('test') .parents('.outer') .html(); alert(tmpl); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
如果您之前没有“ a-href标签”,则可以使用:-
tpl = $(tpl).find('a').eq(0).addClass('myClass');
你需要:
tpl = $(tpl).find('a').addClass('myClass').attr('href');
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.