0

I'm creating a Chrome Extension to highlight the user's name on the page. I am able to detect the name on the page, but I am having difficulty in actually highlighting just the user's name instead of the entire span it is in. Below name_to_highlight is a variable holding a string representation of the name identified.

$( "span:contains('" + name_to_highlight + "')" ).contents().wrap( "<mark></mark>");

EDIT: Thanks to the response, I was able to alter the code so it was applicable to any web page.

// only highlight the child element containing name
  var targets = $( "*:contains('" + name_to_highlight + "')" );
  for(var i = 0; i < targets.length; i++ ){
    if(targets[i].children.length < 1){
    var spanText = targets[i].innerHTML;

    // wrapping a name class around the date
    targets[i].innerHTML = (spanText.replace(name_to_highlight, "<mark>" + 
   name_to_highlight + "</mark>"));
     }
   }
tpinto
  • 41
  • 3

1 Answers1

0

You're part way there, but you are wrapping the entire contents of the element in the <mark> tags. Once you've identified the element, you need to:

  1. Pull the content out,
  2. Target the name specifically and wrap it in the tags, and
  3. Replace the existing content with the updated version

To do that, you're going to need to do some string manipulation . . . something like the below code:

function highlightName(sName) {
  var targetSpan = $("span:contains('" + sName + "')");
  var spanText = targetSpan.text()
  
  targetSpan.html(spanText.replace(sName, "<mark>" + sName + "</mark>"));
}

highlightName('John Smith');
highlightName('Jack Jones');
highlightName('Julie Jones');
mark {background-color: yellow;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<p><span>My name is John Smith and I am new here</span>.</p>
<p><span>My name is Jane Smith and I am a veteran user</span>.</p>
<p><span>My name is John Doe and I am the owner</span>.</p>
<p><span>My name is Jack Jones and I am new here</span>.</p>
<p><span>My name is Julie Jones and I am an amateur user</span>.</p>

NOTE: If there is anything other than text content in the span, the code would need to be updated to preserve the HTML code. Right now, the text() method will pull out only the text content of the <span> and, when it is replaced with the "html() method, only the newly added <mark> tags will remain as child HTML elements.

talemyn
  • 7,822
  • 4
  • 31
  • 52