![](https://box.kancloud.cn/090cf5d15936145f941bae0717014c07_445x275.png)
~~~
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript" src="js/jquery-1.11.1.js"></script>
<script>
$(function () {
alert($('div').length);//3
alert($('#div1').length);//$()获取到的都是一个集合 1
})
</script>
</head>
<body>
<div id="div1" class="box box2" miaov="妙味">aaaaaaa</div>
<div></div>
<div></div>
</body>
</html>
~~~
***
利用length判断是否有元素
![](https://box.kancloud.cn/8ebd359ba99cf86cb518eec5c776713c_816x25.png)
~~~
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>通过length来纠错,发现页面中没有的元素</title>
<script type="text/javascript" src="js/jquery-1.11.1.js"></script>
<script>
$(function(){
var $span = $('#span1'); //这个span并不存在
console.log($span.length); //0 说明页面中没有$span这个元素
$span.html('bbbbb');
})
</script>
</head>
<body>
<div id="div1">aaaaaaa</div>
</body>
</html>
~~~
***
#### 课堂练习--删除指定颜色方块
![](https://box.kancloud.cn/792f7e9fed26813cb7d44f490a0673ca_518x182.png)
![](https://box.kancloud.cn/100fe3a679368948987e0b66e87ee955_495x169.png)
~~~
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
div{
width:100px;
height:100px;
float:left;
margin:10px;
border:1px solid #000;
}
</style>
<script type="text/javascript" src="js/jquery-1.11.1.js"></script>
<script>
$(function () {
var color = '';
$('span').click(function () {
color = $(this).html();
});
$('div').click(function () {
$(this).css('background',color);
});
$('input').click(function () {
$('div[style*=red]').css('background','');
});
})
</script>
</head>
<body>
<span>red</span>
<span>yellow</span>
<span>green</span>
<span>blue</span>
<br>
<input type="button" value="清空红色">
<br>
<div></div>
<div></div>
<div></div>
<div></div>
</body>
</html>
~~~