WP-Mix

A fresh mix of code snippets and tutorials

jQuery Get Number of Paragraphs

Quick jQuery code snippet to get the number of paragraphs in the specified element. The technique can be modified easily to get the number of any element.

Get the number of paragraphs

To get the number of paragraphs contained in an element with class .content, we can do this:

$number_paragraphs = $('.content').find('p').size();

To use this code for your own purposes, change .content to match the selector for which you would like to count paragraphs.

Get the number of paragraphs on click

Here is an example where we get the number of paragraphs when the user clicks the .button element:

$('.button').click(function() {
	$number_paragraphs = $('.content').find('p').size();
	alert($number_paragraphs);
});

This will pop up an alert that shows the number of paragraphs. You can customize as needed for example by changing the button selector from .button to whichever selector you would like to use.

Get the number of any element

Following from the previous examples, we can get the number of any element on the page like so:

$('.button').click(function() {
	$number_divs = $('.content').find('div').size();
	alert($number_divs);
});

Here we are getting the number of <div>s contained within the .content element. To get the number of any other element, change <div> accordingly.

★ Pro Tip:

Banhammer ProWizard’s SQL Recipes for WordPressSAC Pro