tpdietz tpdietz - 5 months ago 9
Javascript Question

Find and replace text portion of html element that may contain children

I am extracting some html from a wysiwyg editor and need to parse and replace the text portion. For example, I might be given html like so:

<span style="font-size: 36px; line-height: 50.4px;">
first text I want to replace
<span style="font-size: 11px;"><i><b>hello world</b></i></span>
second text I want to replace
<span style="font-size: 15px;"><i><b>foo bar</b></i></span>
third text I want to replace
</span>


Let's say I wanted to replace the text portion of the parent span and leave the children elements alone. For example, let's say I wanted to convert the html into this:

<span style="font-size: 36px; line-height: 50.4px;">
I replaced my first text
<span style="font-size: 11px;"><i><b>hello world</b></i></span>
I replaced my second text
<span style="font-size: 15px;"><i><b>foo bar</b></i></span>
I replaced my third text
</span>


The value of the strings before replacement and after replacement is not relevant in this question. I just want to know how I could possible located and replace those strings.

The closest thing I could find online was this nifty trick with jQuery:

$("#span-selector").clone().children().remove().end().text()


However, this will extract all text from the parent, with no way of being able to replace a modified string in its place. How could I use javascript/jQuery to find
first text I want to replace
and replace it with
I replaced my first text


Does anybody think this is possible? Keep in mind I am getting the html directly from an editor, so its possible a user would enter in some characters that appear like html. So I don't know if parsing the html manually looking for '<' and '>' would work.

Kld Kld
Answer

You can get all the children of an element using .contents() then use .eq() to get the element at the specified index and finally replace the elemnt with .replaceWith()

function replaceText() {
  $('#parent').contents().eq(0).replaceWith('<h3>Replaced with HTML</h3>');
  $('#parent').contents().eq(2).replaceWith('replaced 2');
  $('#parent').contents().eq(4).replaceWith('replaced 3');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span id="parent" style="font-size: 36px; line-height: 50.4px;">
    my first text
    <span style="font-size: 11px;"><i><b>hello world</b></i></span>
    my second text
    <span style="font-size: 15px;"><i><b>foo bar</b></i></span>
    my third text
</span>
<button onclick="replaceText()" >Replace</button>

Comments