Home >Web Front-end >JS Tutorial >Master the various selector types and uses in jQuery
jQuery is a popular JavaScript library that simplifies the process of manipulating HTML elements, event handling, animation effects, and Ajax on web pages. When developing with jQuery, it is crucial to be familiar with the various selector types and their uses. Selectors are methods used in jQuery to select specified elements. You can accurately select the elements you want to operate according to your needs, thereby achieving more flexible development.
Element selector: Select all specified elements, the syntax is $("element")
. For example, $("p")
selects all paragraph elements.
$("p").css("color", "red");
ID selector: Select elements with a specific id, the syntax is $("#id")
. For example, $("#myId")
select the element with the id "myId".
$("#myId").hide();
Class selector: Select elements of the specified class, the syntax is $(".class")
. For example, $(".myClass")
selects elements with class "myClass".
$(".myClass").fadeIn();
Descendant selector: Select the descendant elements of the specified element, the syntax is $("parent descendant")
. For example, $("div p")
selects all paragraph elements within div elements.
$("div p").addClass("highlight");
Child element selector: Select the direct child elements of the specified element, the syntax is $("parent > child")
. For example, $("ul > li")
selects the direct child element li under the ul element.
$("ul > li").hover(function(){ $(this).toggleClass("hover"); }); ### 3. 过滤选择器
First element: Select the first matching element, the syntax is :first
. For example, $("li:first")
selects the first li element.
$("li:first").css("font-weight", "bold");
Last element: Select the last matching element, the syntax is :last
. For example, $("li:last")
selects the last li element.
$("li:last").css("color", "blue");
Elements containing specified text content: Select elements containing specified text content, the syntax is :contains(text)
. For example, $("p:contains('Hello')")
selects the paragraph element that contains the text "Hello".
$("p:contains('Hello')").addClass("highlight");
Empty element: Select an empty element without child elements, the syntax is :empty
. For example, $("div:empty")
selects an empty div element.
$("div:empty").text("This div is empty");
Visible elements: Select visible elements, the syntax is :visible
. For example, $("div:visible")
selects visible div elements.
$("div:visible").fadeOut();
Hidden element: Select the hidden element, the syntax is :hidden
. For example, $("div:hidden")
selects the hidden div element.
The above is the detailed content of Master the various selector types and uses in jQuery. For more information, please follow other related articles on the PHP Chinese website!