How to Select All Paragraph Elements in jQuery
This guide provides a direct walkthrough on how to select all
paragraph (<p>) elements on a webpage using jQuery.
You will learn the primary selector syntax, how it works within the
Document Object Model (DOM), and several practical examples
demonstrating how to style, modify, and bind events to every paragraph
on your page simultaneously.
The Basic Selector Syntax
To select all <p> elements on a page, use the
standard tag name selector inside the jQuery wrapper:
$("p");This query searches the entire DOM and returns a jQuery collection
containing every <p> element found on the page.
Common Operations on Selected Paragraphs
Once you have selected all paragraphs, you can apply jQuery methods directly to the entire collection without writing manual loops.
1. Modifying CSS Styles
To change the appearance of all paragraphs at once, use the
.css() method:
// Change text color and font size of all paragraphs
$("p").css({
"color": "#333333",
"font-size": "16px"
});2. Adding or Removing Classes
To apply an existing CSS class to every paragraph:
// Add a class
$("p").addClass("highlight");
// Remove a class
$("p").removeClass("highlight");3. Updating Text or HTML Content
To update the text inside all paragraph elements:
// Update text content
$("p").text("This text replaces the content in every paragraph.");4. Attaching Event Listeners
You can attach an event handler, such as a click listener, to every paragraph:
$("p").on("click", function() {
$(this).toggleClass("active");
});5. Iterating Over Each Paragraph
If you need to perform custom logic on each paragraph individually,
use the .each() method:
$("p").each(function(index) {
console.log("Paragraph " + index + ": " + $(this).text());
});Scoped Paragraph Selection
If you only want to select paragraphs inside a specific container rather than the entire page, prepend the container's identifier to the selector:
// Select all paragraphs inside an element with the ID 'content'
$("#content p");
// Select all paragraphs inside elements with the class 'article'
$(".article p");