Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
872 views
in Technique[技术] by (71.8m points)

jquery - Find a string of text in an element and wrap some span tags round it

I want to find a string of text in an element and wrap some span tags round it. E.g.

From:

<h2>We have cows on our farm</h2>

To:

<h2>We have <span class='smallcaps'>cows</span> on our farm</h2>

I've tried:

$("h2:contains('cow')").each(function() {
 $(this).text().wrap("<span class='smallcaps'></span>");
});

But that only wraps the whole containing h2 tag.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
$("h2:contains('cow')").html(function(_, html) {
   return html.replace(/(cow)/g, '<span class="smallcaps">$1</span>');
});

http://jsfiddle.net/w5ze6/1/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...