Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert text node into HTML element using JQuery

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?

like image 503
Vittorio Romeo Avatar asked Nov 30 '25 06:11

Vittorio Romeo


2 Answers

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>
like image 173
Constantin Groß Avatar answered Dec 01 '25 20:12

Constantin Groß


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>
like image 40
Dalin Huang Avatar answered Dec 01 '25 18:12

Dalin Huang