Course Content
JQUERY Tutorial
About Lesson

Basic selectors

jQuery is a powerful JavaScript library that simplifies HTML document traversing, event handling, and animation for web development. One of its fundamental features is the ability to select and manipulate HTML elements using selectors. In this post, we’ll delve into the basics of jQuery selectors, providing you with a solid foundation for efficient web development.

What are Selectors?

Selectors are a crucial aspect of jQuery, allowing developers to target specific HTML elements and perform actions on them. In essence, selectors act as a bridge between your JavaScript code and the elements on your web page.

Types of Basic Selectors

1. Element Selector

The most straightforward selector, the element selector, targets HTML elements by their tag names. For instance, to select all paragraphs on a page, you would use $("p").

2. ID Selector

Identified by the # symbol, the ID selector targets a specific element with a given ID. For example, $("#myElement") select the element with the ID “myElement.”

3. Class Selector

The class selector, denoted by a dot (.), selects all elements with a particular class. To select all elements with the class “myClass,” you would use $(".myClass").

4. Attribute Selector

Attribute selectors target elements based on their attributes. For instance, [attribute=value] selects elements where the specified attribute has the given value.

Practical Examples

Let’s explore some real-world examples to better understand how these basic selectors work:

// Select all paragraphs and change their text color
$("p").css("color", "blue");

// Select an element by its ID and hide it

// Select all elements with a specific class and apply a border
$(".myClass").css("border", "1px solid black");

// Select elements with a specific attribute and modify their content
$("[data-type='example']").html("New content");

Chaining Selectors

jQuery allows you to chain multiple selectors together, providing a more concise way to apply actions to specific elements. Here’s an example:

// Chain multiple selectors to apply a common style
$("h1, h2, p").css("font-family", "Arial");