js选择器和jquery选择器

1 元素、属性、标签的关系

html文档由嵌套的html元素组成,一个html元素包含开始标签和结束标签。属性是html元素提供的附加信息。

下面的例子中定义了一个div元素

id、name、class是元素属性

而div是组成元素的标签

1
<div id="test-div-id" name="test-div-name" class="test-div-class"></div>

选择器的作用就是获取满足指定条件的元素。这里的条件可以是元素的id、name、标签名、class名,还可以根据元素的属性来进行选择。

js选择器

getElementById()通过元素ID获取元素

getElementsByName()通过元素Name获取元素

getElementsByTagName()通过元素的标签名称获取元素

getElementsByClassName()通过元素的CSS类来获取元素

JQuery选择器

(1)使用元素id、标签名、class选择元素。

1
2
3
4
5
6
*  $("*")  所有元素
#id $("#id1") id="id1"的元素
ele $("p") 所有<p>元素
.class $(".c1") 所有class="c1"的元素
$(".c1.c2") 所有class="c1"且class="c2"的元素
s1,s2,s3 $("th,td,.intro") 所有带有匹配选择的元素

(2) 根据元素所处的位置进行选择

第一个、最后一个、奇数个、偶数个、等于index、大于index、小于index的元素。

1
2
3
4
5
6
7
:first  $("p:first")   第一个 <p> 元素
:last $("p:last") 最后一个 <p> 元素
:even $("tr:even") 所有偶数 <tr> 元素
:odd $("tr:odd") 所有奇数 <tr> 元素
:eq(index) $("ul li:eq(3)") 列表中的第四个元素(index 从 0 开始)
:gt(no) $("ul li:gt(3)") 列出 index 大于 3 的元素
:lt(no) $("ul li:lt(3)") 列出 index 小于 3 的元素

(3)选择不满足某条件的元素

1
:not(selector)  $("input:not(:empty)") 所有不为空的 input 元素

(4)根据元素的属性进行选择
属性(名等于、值(等于、不等于、包含xxx结尾))的元素

1
2
3
4
[attribute]  $("[href]")   所有带有 href 属性的元素
[attribute=value] $("[href='#']") 所有 href 属性的值等于 "#" 的元素
[attribute!=value] $("[href!='#']") 所有 href 属性的值不等于 "#" 的元素
[attribute$=value] $("[href$='.jpg']") 所有 href 属性的值包含以 ".jpg" 结尾的元素

(5)选择表单元素(输入、文本、密码、单选、提交、重置、图片、标题、文件等)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
:input  $(":input")    所有 <input> 元素
:text $(":text") 所有 type="text" 的 <input> 元素
:password $(":password") 所有 type="password" 的 <input> 元素
:radio $(":radio") 所有 type="radio" 的 <input> 元素
:checkbox $(":checkbox") 所有 type="checkbox" 的 <input> 元素
:submit $(":submit") 所有 type="submit" 的 <input> 元素
:reset $(":reset") 所有 type="reset" 的 <input> 元素
:button $(":button") 所有 type="button" 的 <input> 元素
:image $(":image") 所有 type="image" 的 <input> 元素
:file $(":file") 所有 type="file" 的 <input> 元素

:enabled $(":enabled") 所有激活的 input 元素
:disabled $(":disabled") 所有禁用的 input 元素
:selected $(":selected") 所有被选取的 input 元素
:checked $(":checked") 所有被选中的 input 元素

(6)特殊要求的选择

1
2
3
4
5
6
:header $(":header")   所有标题元素 <h1> - <h6>
:animated 所有动画元素
:contains(text) $(":contains('xxx')") 包含指定字符串的所有元素
:empty $(":empty") 无子(元素)节点的所有元素
:hidden $("p:hidden") 所有隐藏的 <p> 元素
:visible $("table:visible") 所有可见的表格
打赏
  • 版权声明: 本博客所有文章除特别声明外,著作权归作者所有。转载请注明出处!
  • Copyrights © 2015-2023 高行行
  • 访问人数: | 浏览次数:

请我喝杯咖啡吧~

支付宝
微信