increase Mather
increase Mather

Reputation: 139

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:

<p>The rain in Spain stays mainly on the plain</p>

$('p').match('/ain/gi').each(function() {
  $(this).wrap('<span class="red"></span>');
});

Upvotes: 0

Views: 106

Answers (2)

David Thomas
David Thomas

Reputation: 253308

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>');
});

Upvotes: 3

Tom Pietrosanti
Tom Pietrosanti

Reputation: 4294

You could use a regex replace:

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

http://jsfiddle.net/husgns7t/

Upvotes: 0

Related Questions