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?

5
  • Why not fix this in the markup instead of band-aid'ing it after the fact with javascript? And maybe give the replaceWith method a lookie loo. Commented Oct 27, 2017 at 14:35
  • This is a duplicate of stackoverflow.com/questions/5291703/… Commented Oct 27, 2017 at 14:38
  • $(this).html() use this Commented Oct 27, 2017 at 14:38
  • 1
    Possible duplicate of jQuery select and wrap textNode Commented Oct 27, 2017 at 14:38
  • @Taplar: I have no control over the markup. Commented Oct 27, 2017 at 14:39

2 Answers 2

3

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>

Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.