2

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 a p tag, containing the same particular word/string. It should not be affected in this process.</p>

1 Answer 1

3

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.