Reputation: 6039
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
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
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
Upvotes: 3