find text and create parent tag jquery

94 views Asked by At

Find text after img tag and create p tag for the text is this possible with jquery please help me

See here ;

<p>
  <img src="img.jpg" />
  Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet
</p>

This is my HTML code i need to create like this

<p>
    <img src="img.jpg" />
    <p>Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet</p>
</p>

Is this possible with jquery

1

There are 1 answers

7
Arun P Johny On BEST ANSWER

You can find the next sibling of the img elements and see whether it is an non-empty text node, if so then wrap it with a p node using .wrap()

$('p img').each(function () {
    var next = this.nextSibling;
    if (next && next.nodeType == Node.TEXT_NODE && $.trim(next.nodeValue) != '') {
        $(next).wrap('<p/>')
    }
})

Demo: Fiddle