0

I am trying to make a simple chrome extension, which can find a text in a webpage and make it bold. When I find a simple text, it works, however, it does not work when an original text includes html tag.

Here are my codes,

$("p:contains(" + "like apple" + )").html(
  function( _ , html ) {
    return html.split("like apple").join("<b>" + "like apple" + "/b>");
  }
)

For example, if I find word "like apple", in <p>I like apple</p>, it becomes <p>I <b>like apple</b></p>.

However, for <p>I like <i>apple</i></p>, the code can not find the words "like apple" because of <i>.

How can I fix the code, which can find a text including html tags and change its css style?

2 Answers 2

1

test if text contains html elements if it has, strip html element to get text.

var text='like <span>apple<span/>'

if(/<[a-z][\s\S]*>/i.test(text)){
var stripped_text=strip(text);
}

function strip(html)
{
var tmp = document.createElement("DIV");
tmp.innerHTML = html;
return tmp.textContent || tmp.innerText || "";
}
Sign up to request clarification or add additional context in comments.

Comments

0

I adjusted it for multiple text replacements:

var customText = ['like apples', 'more apples'];

customText.forEach(function(item){

  $("p:contains(" +item +")").html(
    function( _ , html ) {
      return html.split(item).join("<b>" + item + "</b>");
    }
  )

})

<p>I like apples therefore i will buy more apples today.</p>

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.