Mathew Kurian
Mathew Kurian

Reputation: 6039

How to wrap all text in html with another element?

For instance:

FROM

<div>
   whats up!
   <div> whats up2! </div>
   thank you for your help
   <div></div>
</div>

TO

<div>
   <span>whats up!</span>
   <div><span> whats up2! </span></div>
   <span>thank you for your help</span>
   <div></div> <!---STAYS THE SAME -->
</div>

How would I make something like this in jQuery or pure JavaScript?

Upvotes: 1

Views: 349

Answers (2)

charisis
charisis

Reputation: 1762

Just for completeness, the solution @davids provided, extended to work with deeper hierarchies, can be written as follows in "pure" jquery

$('#container')
.find('*')
.andSelf()
.contents()
.filter(function() {
    return this.nodeType == 3;
})
.wrap('<span>')

This reads as follows: get the full contents for #container and all it's proper DOM children, keep only the text nodes (nodeType == 3) and wrap them in <span>.

Note this will get pretty slow if applied to large DOM trees.

Upvotes: 0

davids
davids

Reputation: 6371

Having this HTML:

<div id="container" >
   whats up!
   <div> whats up2! </div>
   thank you for your help
</div>​​​

You could do something like this:

var nodes = document.getElementById('container').childNodes;

$(nodes).each(function(ind, el){
    if(el.nodeType == 3)
        $(el).wrap('<span>');
    else
        $(el).wrapInner('<span>');
});

​ As far as I know, you can't get text nodes with jQuery (correct me if I'm wrong please'), so you can get them with pure JavaScript and use jQuery's method wrap

http://jsfiddle.net/hyJA6/2/

Upvotes: 3

Related Questions