Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery <br> in html causing consecutive text nodes during unwrap

Consider my three parts of code

<div>
Lorem Ispum dolor sit <span class='highlightYellow'>Amet </span>
<br />Lorem  Ispum <span class='highlightYellow'>dolor</span> sit Amet
</div>

<div>
Lorem Ispum dolor sit <span class='highlightYellow'>Amet </span>
Lorem  Ispum <span class='highlightYellow'>dolor</span> sit Amet
<br />
</div>

<div>
Lorem Ispum dolor sit <span class='highlightYellow'>Amet </span>
Lorem  Ispum <span class='highlightYellow'>dolor</span> sit Amet
</div>

and a button

<button>Unwrap text from .hightlightYellow elements</button>

I'm using this method to unwrap

$(".highlightYellow").contents().unwrap();

When see the childnodes of <div>, by something like $('div')[i].childNodes due to the <br/> tag, the contents within the div becomes multiple consecutive text nodes. how two texnodes come one after another? It is really impossible. But here it comes.

In the third <div>, there is no <br/> tag. So it is working fine. I guessed the <br/> tag only causes this issue. Or is there any other method to overcome this?

Here is the Fiddle, you can see the issues by inspecting element

like image 732
Linga Avatar asked Dec 20 '25 03:12

Linga


1 Answers

http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#ID-1312295772

When a document is first made available via the DOM, there is only one Text node for each block of text. Users may create adjacent Text nodes that represent the contents of a given element without any intervening markup, but should be aware that there is no way to represent the separations between these nodes in XML or HTML, so they will not (in general) persist between DOM editing sessions. The normalize() method on Element merges any such adjacent Text objects into a single node for each block of text; this is recommended before employing operations that depend on a particular document structure, such as navigation with XPointers.

$('div').each(function(i, element) {
    element.normalize(); 
   //The normalize() method removes empty Text nodes, and joins adjacent Text nodes.
});

Example

like image 144
Cheery Avatar answered Dec 21 '25 19:12

Cheery