3

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?

Vittorio Romeo
  • 90,666
  • 33
  • 258
  • 416

2 Answers2

4

this refers to a plain DOM node element that doesn't implement neither an html() nor a text() method. Using $(this), you can make the element into a jQuery collection in order to be able to access the jQuery methods. Then you can use replaceWith() to replace the plain text nodes with the <div>s.

$('div').contents().filter(function()
{
    return this.nodeType === 3;
}).each(function()
{
    $(this).replaceWith("<div>" + $(this).text() + "</div>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
    aaaa
    <span>bbbb</span>
    cccc
    <span>dddd</span>
    eeee
</div>
Constantin Groß
  • 10,719
  • 4
  • 24
  • 50
1

You can also use wrap from jquery to wrap the content with div

.wrap()

Description: Wrap an HTML structure around each element in the set of matched elements.

REF: http://api.jquery.com/wrap/

$('div').contents().filter(function()
{
    return this.nodeType === 3;
}).each(function()
{
    $(this).wrap('<div>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
    aaaa
    <span>bbbb</span>
    cccc
    <span>dddd</span>
    eeee
</div>
Community
  • 1
  • 1
Dalin Huang
  • 11,212
  • 5
  • 32
  • 49