javascript - How do I wrap all text nodes with <p> in a div that also may contain other <p> tags and tags such as <strong> using jQuery? -


i have below example html:

<div> wrap text p includes <strong>this</strong> , <a href="">this</a>. <h1>heading 1</h1> <p>some other text</p> wrap text p includes <strong>this</strong> , <a href="">this</a>. </div> 

the desired result using jquery:

<div> <p>wrap text p includes <strong>this</strong> , <a href="">this</a>.</p> <h1>heading 1</h1> <p>some other text</p> <p>wrap text p includes <strong>this</strong> , <a href="">this</a>.</p> </div> 

i think iterate on contents of div , create group of items wrapped given below

var $group = $();  $('div').contents().each(function () {     if (this.nodetype == 3 || !$(this).is(':header, div, p')) {         if (this.nodetype != 3 || this.nodevalue.trim()) {             $group = $group.add(this);         }     } else {         $group.wrapall('<p />')         $group = $()     } }); $group.wrapall('<p />') 

demo: fiddle


Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -