版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/twilight_karl/article/details/70663317
ID选择器,单个元素
var name = $('#nameinfo');
console.info(name.val());
标签选择器,集合
var span = $("span");
span.css("color","red");
类选择器 ,集合
var text = $(".text");
text.css("color","blue");
选择器并列选择多个,集合
var mul = $("name,.text,textarea");
mul.css("color","yellow");
在ID和类前指明前缀
当同一个class被不同的标签使用时,
// 选择class属性是a的ul标签
$("ul.a").css("color","red");
选择具有多个Class的标签
// 选择class同时为a b 的标签
$(".a.b")
通配选择器
$("ul *").size();
不能直接用value获取 value值。而是用val()方法获取value值
选择器返回集合时,可以用size() 返回集合的长度(或者用length属性)
* $().size()
* $().length
高级选择器
<div class="div">
<ul class="a">
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
<p class="b">段落</p>
<div>
<p>段落</p>
<p>段落</p>
</div>
</div>
后代选择器
某个元素的子节点和孙子节点中的特定节点
等价函数find()
// 选取指定标签下的所有p标签
$(".div p").css("color","red");
// 或者使用find("")
$(".div").find("p").css("color","red");
子选择器
只选择子节点,不选择孙子节点
等价函数children()
// 选择了第一个p标记
$(".div > p").css("color","red");
// 或者使用children("")
$(".div").children("p").css("color","red");
next 选择器
某节点的后一个相邻的同级节点
等价函数next()
// 改变第二个li元素的样式
$(".li + li").css("color","red");
// 或者使用next("")
$(".li").next("li").css("color","red");
nextAll 选择器
某节点后的所有同级节点
~
nextAll()
// .b 后的所有同级p标签
$(".b ~ p").css("color","red");
// 或者nextAll("")
$(".b").nextAll("p").css("color","red");
prev() / prevAll()
同级的上一个节点/ 前面的所有同级节点,与next()类似
siblings()
同级的所有节点,包括前面的后面的(不包括自己)
// 选取所有前面和后面的p标签
$(".b").siblings("p").css("color","red");
nextUntil(“”) / revUntil()
向后遇到指定标签停止 / 向前遇到指定标签停止
PS: find()/children()/next()/nextAll()如果不加参数name参数默认是“*”
属性过滤选择器
[attribute] 获取包含给定属性的元素
[attribute=value] 获取与给定属性值相等的元素集合
[attribute!=value] 获取与给定属性值不等的元素集合(包括没有该属性的)
[attribute^=value] 获取与给定属性值开始的元素集合
[attribute$=value] 获取与给定元素值结尾的元素集合
[attribute*=value] 获取与给定属性值包含value的元素集合
[selector1][selector2][selectorN]
$("ul[id]").addClass("blue") // ul元素中具有id属性的元素
$("ul[id=test]").addClass("blue") // ul元素中具有id属性,并且id=test的元素
$("div[name='names'][value='no']").addClass("blue") // 同时满足 name="names" value="no" 的div元素