matt
matt

Reputation: 44293

jquery wrap found string inside of a span?

How do I look inside of all h3's for a specific string like "New" and wrap that inside of a

<span class="red">New </span>

Upvotes: 0

Views: 3094

Answers (1)

BoltClock
BoltClock

Reputation: 723448

Use the :contains() selector to find the word New in every <h3>, then use .html() with a callback to String.replace() to apply the <span>:

$('h3:contains(New)').html(function() {
    return $(this).html().replace('New', '<span class="red">New</span>');
});

This turns

<h3>New stuff</h3>

into

<h3><span class="red">New</span> stuff</h3>

jsFiddle demo

Upvotes: 4

Related Questions