首先,JavaScript 选择元素
- document.getElementById() 【返回的是元素】
- document.getElementsByName() 【返回的是NodeList】
- document.getElementsByTagName() 【返回的是HTMLCollection】
- document.getElementsByClassName() 【返回的是HTMLCollection】
- document.querySelector() 【使用css 选择器,如:".div1"】(第一个匹配)
- document.querySelectorAll() 【同上】 (返回的是NodeList)
CSS 选择元素
- 基本选择器
- 属性选择器
- 伪类选择器
- 伪元素选择器
jQuery 选择元素
jQuery 选择器会返回一个 jQuery 对象的集合,是一个类数组对象,其顺序与页面中顺序一致。
注意:
ready方法:
$(document).ready(function(){});
的简写:
$(function(){});
类数组的例子:
var a = {0:1,length = 1;};
类数组转换为数组:
a = Array.prototype.slice.call(a);
选择器的例子:
$(function(){
var element1 = $('#box1,#box2');
var element2 = $('#box2');
var element3 = $('.box');
var element4 = $('[name="username"]');
var element5 = $('div');
var element6 = $(document.getElementById('box1'));
console.log(element1);
console.log(element2);
console.log(element3);
console.log(element4);
console.log(element5);
console.log(element6);
});
- jQuery 基本选择器
(a) ID 选择器
(b) 类选择器
(c) 元素选择器
(d) 后代选择器
(e) 属性选择器
d. 后代选择器
<script type="text/javascript">
$('.list > li').addClass('highlight');
</script>
e. 属性选择器
<script type="text/javascript">
// $('.list > li').addClass('highlight');
$('a[href="sdg"]').addClass('highlight');
</script>
- jQuery 筛选器/过滤器
(a)位置筛选器
(b)子元素筛选器
(c)表单筛选器
(d)内容筛选器
(e)其他筛选器
(f)自定义筛选器
a. 位置筛选器
:first; :last; :even; :odd; :eq(n); gt(n); lt(n).后面三个分别为:等于,大于,小于。且n从零开始。
<script type="text/javascript">
$('li:first').addClass('highlight');
$('li:last').addClass('highlight');
$('li:even').addClass('highlight');
$('li:odd').addClass('highlight');
$('li:eq(2)').addClass('highlight');
$('li:gt(2)').addClass('highlight');
$('li:lt(2)').addClass('highlight');
</script>
b. 子元素筛选器
:first-child; :last-child; :first-of-type; :last-of-type; nth-child(); :nth-last-child(); :nth-of-type; nth-last-type; only-child; only-of-type.
<script type="text/javascript">
// 子元素筛选器
$('li:first-child').addClass('highlight');
$('li:last-child').addClass('highlight');
$('li:nth-child(2n)').addClass('highlight');
</script>
:checked; :disabled; :enabled; :focus; :button; :checkbox; :file; :image; :input; :password; :radio; :reset; :selected; :submit; :text.
<script type="text/javascript">
$(':checked').parent().addClass('pa');
</script>
d. 内容筛选器
:empty; :contains(text); :has(selector); parent;
<script type="text/javascript">
// 内容筛选器
$(':empty').addClass('pa');
$(':contains("abc")').addClass('pa');
$('p:has(span)').addClass('pa');
$('p:parent').addClass('pa');
</script>
e. 其他筛选器
:lang(language); :not(selector); :root; :target; :hidden; :visible; :header; :animated.
jQuery 选择器的性能优化
- 尽量使用CSS中有的选择器
- 避免过度约束
- 尽量以ID开头
- 让选择器的右边有更多特征
- 避免使用全局选择器
- 缓存选择器结果