简体   繁体   中英

Wrap a particular text string inside an HTML tag with a <span> using jQuery

I am trying to wrap only a certain word (or even a part of a word) inside a given HTML tag's text content with a span , applying a class to it, using jQuery or plain javascript.

I only got as far as selecting the complete tags that contain the desired word/string, but I don't know how to select and wrap the word/s inside it. All the methods I found do search for a substring, but always select and wrap the whole tag or its complete contents (for example wrapInner() ), which is not what I want.

 $('h3:contains(icular)').wrap("<span class='highlight'></span>");
 .highlight { color: green; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <h3>This is the first of several h3 headings</h3> <h3>This is another h3 heading, containing a particular word</h3> <h3>This is another h3 heading</h3> <h3>This is another h3 heading, again containing a particular word</h3> <h3>This is the way it should look: part<span class="highlight">iculär</span> word</h3> <p>This is ap tag, containing the same particular word/string. It should not be affected in this process.</p>

You can use .each() to iterate all elements containing the word you are looking for, and then perform a .replaceAll() on each element's html:

 const search = 'icular' $('h3:contains(' + search + ')').each( function(index, element) { $(element).html( $(element).html().replaceAll(search, '<span class="highlight">' + search + '</span>') ) })
 .highlight { color: green; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <h3>This is the first of several h3 headings</h3> <h3>This is another h3 heading, containing a particular word and another instance of the same "particular" word</h3> <h3>This is another h3 heading</h3> <h3>This is another h3 heading, again containing a particular word</h3> <h3>This is the way it should look: part<span class="highlight">iculär</span> word</h3>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM