BumbleBee
BumbleBee

Reputation: 10839

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

Upvotes: 2

Views: 210

Answers (2)

Adil Shaikh
Adil Shaikh

Reputation: 44740

Try this -

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

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

Upvotes: 1

Ram
Ram

Reputation: 144739

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

Upvotes: 5

Related Questions