undefined

HTML5新的选择器

HTML5新特性的浏览器支持情况

http://www.caniuse.com/#index

HTML5新的选择器

querySelector

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<script>

//document.getElementById();
//document.getElementsByTagName();

//$('#div1') $('.box') $('ul li')

window.onload = function(){

//var oDiv = document.querySelector('[title=hello]');

var oDiv = document.querySelector('.box'); //只能选择一组中的第一个元素

//alert( oDiv.length );

oDiv.style.background = 'red';


};

</script>
</head>

<body>
<div id="div1" class="box" title="hello">div</div>
<div class="box">div2</div>
</body>
</html>

querySelectorAll

获取一组元素

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<script>

//document.getElementById();
//document.getElementsByTagName();

//$('#div1') $('.box') $('ul li')

window.onload = function(){

var aDiv = document.querySelectorAll('.box'); //获取一组元素

alert( aDiv.length );




};

</script>
</head>

<body>
<div id="div1" class="box" title="hello">div</div>
<div class="box">div2</div>
</body>
</html>

getElementsByClassName

获取一组class元素

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<script>

window.onload = function(){

var aDiv = document.getElementsByClassName('box');

alert( aDiv.length );

};

</script>
</head>

<body>
<div id="div1" class="box" title="hello">div</div>
<div class="box">div2</div>
</body>
</html>

获取class列表属性

–length: class的长度

–add() : 添加class方法

–remove() : 删除class方法

–toggle(): 切换class方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<script>

window.onload = function(){
var oDiv = document.getElementById('div1');

//alert( oDiv.classList ); //类似与数组的对象

//alert( oDiv.classList.length ); //3

//oDiv.classList.add('box4');

//oDiv.classList.remove('box2');

oDiv.classList.toggle('box2');

};

</script>
</head>

<body>
<div id="div1" class="box1 box2 box3">div</div>
</body>
</html>
觉得本站不错,请作者吃根辣条