I have several p inside several li as below and also as https://jsfiddle.net/y5zn538e/
<ul>
<li>
<p> Hello 1</p>
<p> Hello 2</p>
<p> Hello 3</p>
</li>
<li>
<p> Hello 4</p>
<p> Hello 5</p>
<p> Hello 6</p>
</li>
</ul>
I want to wrap a div such that it wraps like the 2nd below
<ul>
<li>
<p> Hello </p>
<div>
<p> Hello </p>
<p> Hello </p>
</div>
</li>
<li>
<p> Hello </p>
<div>
<p> Hello </p>
<p> Hello </p>
</div>
</li>
</ul>
I tried like below:
$('ul li >p:not(:first-child)').wrapAll('<div></div>');
However, that seem to not working.. I mean all it does it take all p and wrap it. I want to be wrapp a div inside each li ?
The problem is,
li > p:not(:first-child)
it collects all child p tags except the first child.so You need to use
.each()
function iterate to allli
.
$('ul li').each(function(){
$(this).find('p:not(:first-child)').wrapAll('<div></div>');
});
$('ul li').each(function(){
$(this).find('p:not(:first-child)').wrapAll('<div></div>');
});
div{
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>
<p> Hello 1</p>
<p> Hello 2</p >
<p> Hello 3</p>
</li>
<li>
<p> Hello 4</p>
<p> Hello 5</p >
<p> Hello 6</p>
</li>
</ul>