1.getAttribute和setAttribute
<div class="demo" id="ABC" title="鼠标"></div> <script> var divs = document.getElementById("ABC"); alert(divs.getAttribute("class")); //class="demo" alert(divs.getAttribute("title")); //title="鼠标" divs.setAttribute("id","DEMO"); //class="DEMO" </script>
2.removeChild
divs.removeAttribute("title"); //删除title属性
3.appendChild和 insertbefore
var ul=document.getElementsByTagName(ul); var lis=ul.children; for(var i=0;i<lis.length;i++){ var newspan = document.createElement("span"); newspan.innerHTML=i+1; circle.appendChild(newspan); }在circle div中追加span标签,标签内容为i当前的数字。 实现的效果是在轮播图中ul中添加li小圆圈。
A.append(B) //意思是在A中添加B,B是A的孩子。
A.insertbefore(B,C) //B,C都是A的孩子,都在A中,但是把B插入A中的时候一定是在C的前面位子。
微博发布
<style> ul{ list-style: none; } .box{ margin: 100px auto; width: 600px; height:auto; border:1px solid #ccc; padding: 20px 0; } textarea{ width: 400px; resize: none; } .box li{ width: 400px; line-height: 20px; border-bottom:1px dashed #ccc; margin-left: 50px; } .box li a{ float: right; } </style> </head> <body> <div class="box"> 微博发布: <textarea name="" id="aaa" cols="30" rows="10"></textarea> <button>发布</button> <ul id="ul"> <li>111</li> <li></li> <li></li> </ul> </div> <script> window.onload=function () { var btn = document.getElementsByTagName("button")[0]; var txt = document.getElementsByTagName("textarea")[0]; var ul = document.createElement("ul"); btn.parentNode.appendChild(ul); btn.onclick = function () { if(txt.value==""){ alert("请输入数字"); return false; } var newli = document.createElement("li"); newli.innerHTML=txt.value+"<a href='javascript:;'>删除</a>"; var lis = ul.children; if(lis.length==0){ ul.appendChild(newli); }else{ ul.insertBefore(newli,lis[0]); } var as =document.getElementsByTagName("a"); for(var i=0;i<as.length;i++){ as[i].onclick=function () { ul.removeChild(this.parentNode); } } } } </script> </body>