I need to know how many <p>
has a <div>
, example:
<div class="body">
<p>Lorem ipsum dolor sit amet consectetur adipiscing elit.</p>
<p>Lorem ipsum dolor sit amet consectetur adipiscing elit.</p>
<p>Lorem ipsum dolor sit amet consectetur adipiscing elit.</p>
<p>Lorem ipsum dolor sit amet consectetur adipiscing elit.</p>
<p>Lorem ipsum dolor sit amet consectetur adipiscing elit.</p>
<span>Lorem ipsum dolor sit amet consectetur adipiscing elit.</span>
<div class="paragraphs">
<p>Lorem ipsum dolor sit amet consectetur adipiscing elit.</p>
</div>
</div>
I am only interested in knowing the amount of <p>
it has <div class="body">
more, not the ones that others contain <div>
. In this case the result would have to be 5 and not 6.
Use
document.querySelectorAll('.body > p')
to get all the paragraphs inside the div with classbody
and there you have the count. The>
is to include only the direct paragraphs, without it, the one inside would also countparagraphs
:you can try with
$('div.body').find('p').length
EDIT
the above answer will return all the elements
p
, if you only want the body div thing, then with$('div.body').children('p').length
Keep in mind that if there is another
div
with the same classbody
, it can cause problems, it would be best to put an idP.S. Triby's solution seems more appropriate to me since it is pure js, anyway I leave this with JQuery in case you need it