'Jquery- Find a word in a sentence and add span

I am writing a function to find word in a sentences and add span on top. This is the code but it is not working. Can anyone point out my mistake? Thanks

  function find_and_add(element = "", findWord = "") {
      $(element).each(function() {
        var arr = $('h1 a', this).text().split(' ');
        var newTitle = "";
        $.each(arr ,function(key, value) {
          if (value == findWord) {
            newTitle += "<span>"+ value + "</span><br/>";
          } else {
            newTitle += value + " ";
          }
        });
        $("h1 a", this).html(newTitle);
      });
    }
    
    find_and_add('.wrapper', 'BMW');
    find_and_add('.wrapper', 'Toyota');
    find_and_add('.wrapper', 'Ferrari');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
  
  <h1> 
     <a href="#"> Brand name BMW </a>
  </h1>
  <h1> 
     <a href="#"> Brand name Toyota </a>
  </h1>
  <h1> 
     <a href="#"> Brand name Ferrari </a>
  </h1>
 
</div>


Solution 1:[1]

Please find the jsfiddle that is working for the question below

https://jsfiddle.net/princedc/mg7bkeas/

I am processing every thing on one function call this will ensure better performance. I pass all the words to be changed with one function call. The substitution you are making has to be changed as we need to replace the element alone $(this) in jquery.

function find_and_add(element = "", findWord = "") {
          var lookUpWords = findWord.split(' ');
      $(element).each(function() {
        var arr = $('h1 a', this);
        //console.log(arr);

        $.each(arr ,function(key, value) {
          debugger;
            console.log(value);
          var newTitle = "";
          var words = value.text.split(' ');
          $.each(words,function(wkey,wvalue){
             if (lookUpWords.indexOf(wvalue) >= 0) {
              newTitle += "<span>"+ wvalue + "</span><br/>";
            } else {
              newTitle += wvalue + " ";
            }

          });
         $(this).html(newTitle);

        });
        //$("h1 a", this).html('').html(newTitle);
      });
    }

    find_and_add('.wrapper', 'BMW Toyota Ferrari');
    //find_and_add('.wrapper', 'Toyota');
    //find_and_add('.wrapper', 'Ferrari');

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Chennai Coder