Consider the following HTML:
<div>
aaaa
<span>bbbb</span>
cccc
<span>dddd</span>
eeee
</div>
I use JQuery to match the [aaaa, cccc, eeee]
text nodes by following the answers in this question:
$('div').contents().filter(function()
{
return this.nodeType === 3;
});
Now, I want to replace every text node with an HTML element - say a <div>
containing the text node. This is my desired result:
<div>
<div>aaaa</div>
<span>bbbb</span>
<div>cccc</div>
<span>dddd</span>
<div>eeee</div>
</div>
I've tried to use various closures passed to .each
. E.g.:
$('div').contents().filter(function()
{
return this.nodeType === 3;
}).each(function()
{
this.html("<div>" + this.text() + "</div>");
});
But it seems that the text nodes do not provide any .html
method. How can I replace a text node with an arbitrary HTML element using JQuery?