简体   繁体   中英

Wrap text inside html tag

I am trying to wrap text in inside <span> tag using jQuery. The below code is not working. Please point out where I am going wrong. Also please suggest a better/different approach.

var mysearch = '(05/13/2012-11/13/2012)';
$('table:eq(0) tr:eq(1) th:contains("' + mysearch + '")').filter(function () {
    return this.html().replace('(05/13/2012-11/13/2012)', '<span class = "red"> (05/13/2012-11/13/2012)</span>');
});

Demo on jsFiddle

this in your code is a DOM Element object that doesn't have html method, also you don't need the filter method, you can use html method.

$('table:eq(0) tr:eq(1) th:contains("' + mysearch + '")').html(function(_, html) {
    return html.replace('(05/13/2012-11/13/2012)', '<span class="red"> (05/13/2012-11/13/2012)</span>');
});

If the content of the th is equal to mysearch string, you can also use wrapInner method:

$('table:eq(0) tr:eq(1) th').filter(function(){
    return $.trim($(this).text()) === mysearch;
}).wrapInner('<span class="red"></span>');

JS Fiddle

Try this -

$('table:eq(0) th:contains("' + mysearch + '")').contents().wrapAll('<span class = "red"></span>');

Working Demo --> http://jsfiddle.net/8kMqW/2/

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