Basic selector and level selector for jQuery selector

  • 2020-05-10 17:40:44
  • OfStack

Basic selector

The basic selector is the most commonly used selector in jQuery, and the simplest selector, which looks for DOM elements through elements id, class, tag names, and so on. Each id name can only be used once in a web page, and class allows reuse.

       选择器       描述 返回                示例
#id 根据给定的id匹配1个元素 单个元素 $("#test")选取id为test的元素
.class 根据给定的类名匹配元素 集合元素 $(".test")选取所有class为test的元素
element 根据给定的元素名称匹配元素 集合元素 $("p")选取所有的<p>元素
* 匹配所有的元素 集合元素 $("*")选取所有的元素
selector1,selector2,...selectorN 将每1个选择器匹配到的元素合并后1起返回 集合元素 $("div,span,p.myclass")选取所有<div>,<span>和拥有class为myclass的<p>标签的1组元素

Level selector

If you want to get specific elements through hierarchical relationships between DOM elements, such as descendant elements, child elements, adjacent elements, and peer elements, then the hierarchical selector is a good choice.

选择器                 描述 返回 示例
$("ancestor descendant") 选取ancestor元素里的所有
descendant(后代)元素
集合元素 $("div span")选取<div>里
所有<span>元素
$("parent>child") 选取parent元素下的child元素,
与$("ancestor descendant")有区别,
$("ancestor descendant")选择的是后代元素
集合元素 $("div>span")选取<div>元素下
元素名是<span>的子元素
$("prev+next") 选取紧邻在prev元素之后
的next元素
集合元素 $(".one+div")选取class为one的
下1个<div>同辈元素
$("prev~siblings") 选取prev元素之后的所有
siblings元素
集合元素 $("#two~div")选取id为two的
元素后面的所有<div>同辈元素

The equivalence between the   $("prev+next") selector and the next() method

                    选择器                    方法
                  等价关系              $(".one+div")        $(".one").next("div")

The equivalence relationship between the   $("prev~siblings") selector and the nextAll() method

选择器 方法
等价关系 $("prev~div")
$("#prev").nextAll("div")

That's all for this article, I hope you enjoy it


Related articles: