Skip to content Skip to sidebar Skip to footer

How Can I Find Text In HTML With JQuery?

Is there a way to perform a search some HTML and whenever it finds an occurrence of a regular expression, wrap it in a span? For example:

The rain in Spain stays mainly on

Solution 1:

I'd strongly suggest the following, simpler, approach:

// selects the 'p' elements, and calls the 'html()' method:
$('p').html(function (i,h) {
    // uses the anonymous function, i is the index of the current element
    // from the collection, h is the found HTML of that element.
    return h.replace(/(ain)/gi, '<span class="red">$1</span>');
});

Solution 2:

You could use a regex replace:

$('p').html($('p').text().replace(/(ain)/gi, '<span class="red">$1</span>'));

http://jsfiddle.net/husgns7t/


Post a Comment for "How Can I Find Text In HTML With JQuery?"