lgants lgants - 1 month ago 6x
HTML Question

How do I insert multiple spans into an HTML element at specified indices?


I’m implementing a feature that allows users to capture and persist their highlights using JavaScript/jQuery/HTML/CSS for frontend and Ruby/Rails for backend. I’ve already created a feature to persist highlights in the database, which are nested in an array (i.e.

[[<start_highlight_index >,<end_highlight_index >],…]
). But, I still need to implement a feature to load existing highlights on page load.

Simplified Example:

Given a paragraph element
<p>Hello world</p>
and an array of
, what is the best way to create the following element:

<p><span style="background-color:yellow">Hello</span> <span style="background-color:yellow">world</span></p>

Note that spans were inserted to highlight “Hello” and “world”. Although there are multiple ways to implement this, it’d be great to hear your suggestions for efficient ways to do this, since I want to keep the page load times to a minimum.


Here's javascript code which works for your purpose

  var content = $("p").html();
  var arr = [[1,4],[6,10]];
  var newHTML = "";
  prevIndex = 0;
    newHTML += content.substring(prevIndex, item[0]);
    newHTML += '<span style="background-color:yellow">' + content.substring(item[0], item[1]) + '</span>';
    prevIndex = item[1];
  newHTML += content.substring(prevIndex, content.length);