jQuery selector introduction and classification analysis
jQuery is an extremely popular JavaScript library that is widely used in web development. Among them, selectors are a very important part of jQuery, which allow developers to select elements from HTML documents and operate on them through concise syntax. This article will briefly introduce the basic concepts of jQuery selectors, analyze their classification in detail, and provide specific code examples to help readers better understand.
When using jQuery, selectors are used to specify the HTML elements that need to be operated, and their syntax is similar to CSS selectors. Through selectors, you can select a single element, a group of elements, or all elements in the entire page to easily operate on them, modify styles, or bind events.
Basic selector is used to select a single element or a group of elements in an HTML document. Commonly used basic selectors include:
$("element")
. For example, to select all <p></p>
elements: $("p")
. $("#id")
. For example, select the element with the id "demo"
: $("#demo")
. $(".class")
. For example, select the element with class "info"
: $(".info")
. $("[attribute='value']")
. For example, select the element whose attribute data-id
has the value "123"
: $("[data-id='123']")
. The hierarchical selector is used to select the hierarchical relationship of elements. Commonly used hierarchical selectors include:
$("parent descendant")
. For example, to select all <p></p>
elements inside <div>: <code>$("div p")
. $("parent > child")
. For example, to select all <span></span>
elements directly under <div>: <code>$("div > span")
. $("prev next")
. For example, select a <span></span>
element immediately after the <p></p>
element: $("p span")
. Filter selector is used to select elements that meet specified conditions. Commonly used filter selectors include:
<!DOCTYPE html> <html> <head> <title>jQuery选择器示例</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> </head> <body> <div> <p>Hello, jQuery!</p> </div> <div id="example"> <p class="info">This is a paragraph.</p> <p>This is another paragraph.</p> </div> <script> // 基础选择器示例 $("p").css("color", "blue"); // 改变所有<p>元素的颜色为蓝色 $("#example .info").html("Updated content"); // 修改id为example内class为info的元素的内容 // 层级选择器示例 $("div > p").css("font-weight", "bold"); // 选取div下的直接子元素p并设置字体加粗 // 过滤选择器示例 $("p:first").css("background-color", "yellow"); // 选取第一个<p>元素并设置背景色为黄色 </script> </body> </html>
The above is the detailed content of Introduction to jQuery selector and classification analysis. For more information, please follow other related articles on the PHP Chinese website!