Syntax for a Basic jQuery Selector

This article provides a straightforward overview of the basic jQuery selector syntax, explaining how the selector function is structured to target HTML elements, classes, and IDs for Document Object Model (DOM) manipulation.

The standard syntax for a basic jQuery selector consists of the dollar sign ($), a pair of parentheses, and a string containing a CSS-style selector:

$("selector")

Alternatively, the keyword jQuery can replace the $ alias:

jQuery("selector")

The Three Basic Selectors

jQuery borrows heavily from CSS selector syntax to locate elements on a webpage. The three fundamental selectors are:

  1. Element Selector
    Targets elements by their HTML tag name.
    Syntax: $("tagname")
    Example: $("p") selects all <p> elements on the page.

  2. ID Selector
    Targets a single unique element using its id attribute, prefixed by a hash symbol (#).
    Syntax: $("#id-name")
    Example: $("#header") selects the element with id="header".

  3. Class Selector
    Targets all elements sharing a specific class, prefixed by a period (.).
    Syntax: $(".class-name")
    Example: $(".highlight") selects all elements with class="highlight".

Practical Usage

Once a selector targets an element, jQuery methods are chained to perform actions, such as modifying content, changing styles, or attaching event listeners.

// Hide all paragraph elements
$("p").hide();

// Change the text color of an element with the ID 'intro'
$("#intro").css("color", "blue");

// Add a click event to all elements with the class 'btn'
$(".btn").click(function() {
    alert("Button clicked!");
});

Combining Selectors

Multiple elements can be targeted simultaneously by separating selectors with a comma inside the quotation marks:

// Selects all <h1>, <h2>, and <p> elements
$("h1, h2, p").addClass("text-styled");