简体   繁体   中英

Highlighting in between html tags ( HTML, JavaScript, ReactJS)

I have an API call in my program where the result is an HTML document. I have to show the HTML codes from the API result into my browser. I am also getting two integer values from the API (say, start_point and end_point). My requirement is to highlight the text in HTML document. The text is highlighted from the start_point value to the end_point value. Assume the following HTML code is from my API

<section>
    <p>Lorem ipsum dolor init </p>
    <p>Lorem ipsum dolor init </p>
      <div>
        <p>Lorem ipsum dolor init </p>
        <p>Lorem ipsum dolor init </p>
      </div>
    <p>Lorem ipsum dolor init </p>
    <p>Lorem ipsum dolor init </p>
  </section>

Now consider and .

So according to my requirement, since the start_point is 16 and end_point is 32, the counting starts from "<" of the <section> tag, and highlight starts from "r" of Lorem and end in "i" of init in the < h1> tag. So the above html will be shown in my browser somewhat like this:

Lo rem ipsum dolor i nit

Lorem ipsum dolor init

Lorem ipsum dolor init

Lorem ipsum dolor init

Lorem ipsum dolor init

Lorem ipsum dolor init

But now consider the case that the start_point is in the middle of some tag and end_point is after the closing of the same tag.

For example, consider and . So my HTML highlight should look like this:

Lorem ipsum dolo r init

Lor em ipsum dolor init

Lorem ipsum dolor init

Lorem ipsum dolor init

Lorem ipsum dolor init

Lorem ipsum dolor init

Is there any way to achieve this?

Presently I am using a JavaScript code like this:


html.slice(0, start_point) + `<span id="highlightText">` + html.slice(start_point + 25, end_point) +`</span>` + html.slice(end_point);

Here <span id="highlightText"> takes 25 space, that is why I have added 25 to the second slice. This span with id "highlightText" is then given a background color. Since I have to close the span tag inside the container tag, it is not working. I dont want to use jQuery so please suggest pure JavaScript answers.

At last, I found the solution. MarkJS helped me to achieve what I actually needed. It handles the highlighting of text even if it crosses HTML tags. A perfect solution for my problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM