3gwebtrain
3gwebtrain

Reputation: 15303

how to unwrap the multiple parents elements

i am getting the html decoded from server. once i receive that's look like this:

it has spans simply nested inside of no.of span's

<p><span><span><span><span>The portacabin consist of toilets, <strong></strong> <strong>\u003e\u0026#160;</strong> showers and changing cubicles, a classroom, an office and a store room.&nbsp;<br>The
 upgrade shall include development of foot paths and installation of new
 up-lights around the area complete with all the required &amp; 
necessary directional signages, as per the Standards Engineering 
Specification &amp; approval by client.</span></span></span></span></p>

I would like to remove the span whichever not required, even if it has only space. how to do this?

i tried this:

var p = $('p').contents().unwrap();

console.log(p);

there is a empty strong element and with only space with strong elment - how to clear it?

It unwraps step, that's it. Any one help me please?

Live

Upvotes: 0

Views: 84

Answers (1)

blgt
blgt

Reputation: 8205

You can use the .nodeType property to test for text-level nodes, then match them against the whitespace regex /\s*/:

if (this.nodeType === Node.TEXT_NODE) {
    this.innerText.match(/\s*/) && $(this).unwrap();
}

You can place that in a loop with the .each() function to flatten each level of span-s, and iterate that over all spans. Here's a fiddle showing a basic version of this: http://jsfiddle.net/LwmoLp3o/2/

Upvotes: 1

Related Questions