<style>
html,body{
margin: 0;
padding: 0;
}
div:not(:nth-of-type(2)){
margin:0;
width:500px;
height:100%;
background-color: #f40;
margin-top: 50px;
}
/*ul默认有外边距*/
ul{
width: 300px;
height: 100%;
background-color: #BDBDBD;
list-style: none;
/*清除默认边距*/
margin:0;
padding:0;
margin:20px auto;
margin-bottom:30px;
}
li{
width: 200px;
height: 30px;
line-height: 30px;
margin: 20px auto;
background-color: pink;
}
</style>`在这里插入代码片`
<div id="box5">我是div5
<button id="btnAdd">添加元素</button>
<button id="btnRemove">删除元素</button>
<ul id="list3">我是ul3
<li>我是li1</li>
<li>我是li2</li>
<li>我是li3</li>
</ul>
</div>
<script>
var btnAdd=document.getElementById("btnAdd");
var btnRemove=document.getElementById("btnRemove");
var ul3=document.getElementById("list3");
//通过css选择器获取ul中所有的li元素,返回一个类数组
//var liList=document.querySelectorAll("#list3 li");
var liList=document.getElementsByTagName('li');
var str="我是li";
var num=3;
//循环给每个li元素注册鼠标移入移出事件
function mHover(){
for(var i=0;i<liList.length;i++){
liList[i].onmouseover=function(){
this.style.backgroundColor="yellow";
};
liList[i].onmouseout=function(){
this.style.backgroundColor="skyblue";
}
}
console.log(liList);
console.log(liList.length);
}
mHover();
//给添加按钮添加点击事件,实现添加li元素的功能
btnAdd.onclick=function(){
num++;
//创建li元素节点
var nli=document.createElement("li");
//创建文本节点
var textNode=document.createTextNode("我是li"+num);
//将文本节点插入到li元素中
nli.appendChild(textNode);
//将组合后的li元素,在放入到ul元素内部子元素的末尾
ul3.appendChild(nli);
//动态添加li元素后,希望给他们也添加上鼠标移入移出事件,此处执行此函数即可实现
mHover();
}
//给按钮添加点击事件,并实现删除li元素的功能
btnRemove.onclick=function(){
//删除增加的那个li元素
ul3.removeChild(ul3.lastElementChild);
num--;
//如果没有这条语句,那么新增的li元素不会拥有鼠标移入移出事件
mHover();
}
</script>
以上程序演示了
document.querySelectorAll(“元素选择器类型”),返回的是一个NodeList
NodeList的特点是:其里面的内容是静态不变的,不会随着dom元素的变化而改变。
document.getElementsByTagName(‘元素选择器类型’),返回的一个HTMLCollection
HTMLCollection的特点是,其内容是动态的,会随着dom的元素的更改而改变。
版权声明:本文为weixin_37164418原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。