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 >iculär</span> word</h3>
<p>This is a p tag, containing the same particular word/string. It should not be affected in this process.</p>
CodePudding user response:
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 >' 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 >iculär</span> word</h3>