Great Day Today Great Day Today - 3 months ago 5
HTML Question

How to check if a span is a parent of another span, then destroy the child span?

Let's say I have the following:


Hi, my
<span class='green_mark'>
name is
<span class='red_mark'>
Bob
</span>
. How are
</span>
you doing?


In this example, green_mark already covers the content of red_mark. Is there some way to detect if a span parent covers a span child? Then, destroy the span that is the child?

In this case, I see that
.green_mark
is the parent,
.red_mark
is the child. Therefore, I want
.red_mark
destroyed.

Note: I have the highlighting done in JS, but send data over PHP. Therefore, this solution can either be JS or PHP...

K K K K
Answer

Try this:

$(document).ready(function() {
  $("span.green_mark>span.red_mark").each(function() {
    var elem = $(this);
    var text = elem.text();
    elem.replaceWith(text);
  });
});

Or

$(document).ready(function() {
  $("span.green_mark span.red_mark").each(function() {
    var elem = $(this);
    var text = elem.text();
    elem.replaceWith(text);
  });
});

Demo: http://jsfiddle.net/GCu2D/1502/

The first code works for the immediate red_mark child of green_mark while the second one is for any red_mark child within green_mark

Comments