Jerpl Jerpl - 4 months ago 24
jQuery Question

If element contains any of these words then wrap that word in span

I'd like to highlight certain words if they're found within a title by wrapping those words in a span class. Is there a way of writing a list of words to check for and then using the same command to wrap any of those words with the span class?

For example:

<h1>This title contains the word Balloon</h1>
<h1>This title contains the word Oranges</h1>
<h1>This title doesn't contain either of those terms</h1>


Something to check each of those three elements (but there would be 20 or so) for the words Balloon or Oranges and then wrap just those words in a span color.

I could use:

$('h1').html($('h1').html().replace(/(balloon)/g,'<span class="red">balloon</span>'));


but I'd have to write that query for every word, whereas I'd like something a little simpler, if possible.

Answer

Loop through your element set, like so, and replace it with anything in an array of keywords:

<h1>This title contains the word Balloon</h1>
<h1>This title contains the word Oranges</h1>
<h1>This title doesn't contain either of those terms</h1>
<h1>This title contains both Balloon and Oranges</h1>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>

<script>
var wordsToHighlight = ['Balloon', 'Oranges'];
$('h1').each(function() {
  for (var i = 0, l = wordsToHighlight.length; i < l; i++) {
    if ($(this).html().indexOf(wordsToHighlight[i]) !== -1) {
      var newValue = $(this).html().replace(wordsToHighlight[i], 
          '<span>' + wordsToHighlight[i] + '</span>');
      $(this).html(newValue);
    }
  }
});
</script>
Comments