gruber
gruber

Reputation: 29749

Create new node from text inside paragraph

I have a site with a lot of paragraphs. Some of them have text and image:

<p>first paragraph</p>
<p>second paragraph</p>
<p>third paragraph</p>
<p>fourth paragraph<img alt="alt" src="src"/></p>
<p>fifth paragraph</p>

I would like to have numbered paragraphs with the <img> tags wrapped in new paragraphs:

<p id="1">first paragraph</p>
<p id="2">second paragraph</p>
<p id="3">third paragraph</p>
<p id="4">fourth paragraph</p>
<p id="5"><img alt="alt" src="src"/></p>
<p id="6">fifth paragraph</p>

Please note that if the text inside paragraph 4 is after the image, then the final situation should be:

<p id="1">first paragraph</p>
<p id="2">second paragraph</p>
<p id="3">third paragraph</p>
<p id="4"><img alt="alt" src="src"/></p>
<p id="5">fourth paragraph</p>
<p id="6">fifth paragraph</p>

Now I have only this code, but it doesn't add the image into a separate paragraph:

elem.find('p').each(function () {
    id++;
    $(this).attr('id', 'id_' + id);
});

Upvotes: 2

Views: 176

Answers (2)

David Thomas
David Thomas

Reputation: 253396

One approach:

$('p').each(
    function(i){
        while(this.childNodes.length > 1) {
            var p = document.createElement('p');
            p.appendChild(this.childNodes[1]);
            this.parentNode.insertBefore(p,this.nextSibling);
        }
    });

$('p').attr('data-index',function(i) { return i; });​​​​​​​​​​​

JS Fiddle demo.

I've amended the first chunk of code in order to preserve the order of the childNodes (which is flawed in this example using the above code (check out the second textNode following the img, it's in the wrong place):

$('p').each(
    function(i){
        while(this.childNodes.length > 1) {
            var p = document.createElement('p');
            p.appendChild(this.lastChild);
            this.parentNode.insertBefore(p,this.nextSibling);
        }
    });

JS Fiddle demo.

Upvotes: 3

VVV
VVV

Reputation: 7593

How about this fiddle

$('p').each(function(index, p) {
    p.find('img').each(function() {
        if (p.text() != '') {
            var newParagraph = $('<p></p>');
            var html = p.html();
            newParagraph.append($(this));

            if (html.substring(0,1) != '<') {
                p.after(newParagraph);
            }
            else {
                p.before(newParagraph);
            }

        }         
    });
});

$('p').each(function(i) {
   $(this).attr('id', i);
});

Upvotes: 0

Related Questions