Search code examples
javascriptjquerydomword-wrap

Wrap some text of an element in a span with Jquery?


I have an HTML article with some annotations on it, this annotation refers to some text inside the body. I want to wrap this text in a <span> tag so that I can modify it as I want.

I have a SPARQL Query that returns me some info and three important variables:

element --> the id of the container element of the text

start --> position of the first character of the annotation inside the element

end --> position of the last character of the annotation inside the element

Below there is an example that maybe will clarify.

With this element:

    <p class="metadata-entry" id="element_id">
    <span class="generated" id="span1">Publisher: </span>
    BioMed Central
    <span class="generated" id="span2"> (</span>
    London
    <span class="generated" id="span3">)</span>
    </p>

Since I have an annotation on the word "London" when I run my query I obtain:

element = "element_id"
start = 27
end = 33

Now, after my ajax call that returns these 3 values, how can I wrap the word "London" in a span so I can set its background to a specific color?


Solution

  • This may be a bit dirty, but I think it should work. Since you have the element that contains "London", you can replace the HTML of that element with a modified version of what's currently in there.

    You can see how to use the jquery html function here:

    How to replace innerHTML of a div using jQuery?

    Basically, what you'd do is use it as a getter to get the HTML out of the "element_id" element, modify it using Javascript string functions by adding span tags at the start and end indexes you have, and then using the html function to replace "element_id"'s HTML with the modified string.

    I hope this works for you!

    EDIT: To illustrate this better, here's essentially what you'd be doing:

    var currentHTML = $(element).html();
    var newHTML = currentHTML.substring(0, start) + "<span style='background-color: green;'>" + currentHTML.substring(start, end) + "</span>" + currentHTML.substring(end, currentHTML.length);
    $("element_id").html(newHTML);