获取所有的div和p标签,并为其加上背景颜色
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
div{
width: 100px;
height: 30px;
border: 1px solid #fff;
padding: 5px 5px;
}
p{
width: 100px;
height: 100px;
display: block;
margin-top: 50px;
}
</style>
</head>
<body >
<div ></div>
<div></div>
<p></p>
<p></p>
</body>
</html>
<script>
//函数封装
var dom = function(tag){
return document.getElementsByTagName(tag);
}
var divs = dom('div');
var spans = dom('p');
var each = function(arr,col){
for(var i=0;i<arr.length;i++){
arr[i].style.background= col;
}
}
each(divs,'red');
each(spans,'#000');
</script>