Skip to main content

Archive

Show more

jQuery Selectors

jQuery - Selectors

Selectors in jQuery are powerful tools for targeting specific elements in an HTML document, allowing developers to manipulate them dynamically.


1. Element Selectors

Element selectors target HTML elements based on their tag names. Here's an example:

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

This code selects all <p> paragraphs in the document and changes their text color to red.

<p>This is paragraph</p>

2. ID Selectors

ID selectors target elements based on their unique IDs. Here's an example:

// Select element with ID "myElement" and hide it
$("#myElement").hide();

This code selects the element with the ID "myElement" and hides it from view.

<p id="myElement">This is my element.</p>

3. Class Selectors

Class selectors target elements based on their CSS classes. Here's an example:

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

This code selects all elements with the class "myClass" and adds a black border to them.

<p class="myClass">This is my class.</p>

4. Attribute Selectors

Attribute selectors target elements based on their attributes and attribute values. Here's an example:

// Select all input elements with type "text" and set their background color to yellow
$("input[type='text']").css("background-color", "yellow");

This code selects all <input> elements with the type "text" and sets their background color to yellow.

<input type="text" id="name" name="name" required minlength="4" maxlength="8" size="10" />

5. Conclusion

Understanding and utilizing selectors effectively is crucial for harnessing the full power of jQuery in selecting and manipulating elements within your web pages.

Comments