文档对象模型(Document Object Model,DOM)是一种用于HTML和XML文档的编程接口。它给文档提供了一种结构化的表示方法,可以改变文档的内容和呈现方式。我们最为关心的是,DOM把网页和脚本以及其他的编程语言联系了起来。DOM属于浏览器,而不是JavaScript语言规范里的规定的核心内容。
一,查找元素:
1,直接查找
document.getElementById 根据
ID
获取一个标签
document.getElementsByName 根据name属性获取标签集合
document.getElementsByClassName 根据
class
属性获取标签集
docum
ent.getElementsByTagName 根据标签名获取标签集合
<div class="c1">哈哈</div> <div id="l">嘿嘿</div> <input type="text" name="xin"/> <p>哈哈</p> <script> var ww = document.getElementsByClassName('c1'); var xx = document.getElementById('l'); var cc = document.getElementsByName("xin"); var dd = document.getElementsByTagName("p"); </script>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> </style> </head> <body> <div> <div id="num">1</div> <input type="button" value="+1" onclick="add()"/> </div> <div> <div id="n1">哈哈</div> <a>笑什么</a> </div> <ul> <li>123</li> <li>123</li> <li>123</li> </ul> <div> <div class="c1">1</div> <div class="c1">2</div> <div class="c1">3</div> </div> <form> <p>用户名:<input name="user" value="123"/></p> <p> 密码:<input name="pwd" value="456"/></p> </form> <script type="text/javascript"> function add(){ // alert(123); 弹窗 var nid = document.getElementById("num"); var text = nid.innerText; text = parseInt(text); text += 1; nid.innerText =text; } var n1 = document.getElementById('n1'); n1.innerText="凯欣"; 修改制定的字符串 /////////// var lis = document.getElementsByTagName("li"); for(var i in lis){ var item = lis[i]; item.innerText = i; } /////////// var lis2 = document.getElementsByClassName("c1"); for (var i in lis2){ var item = lis2[i]; item.innerText = i; } //////////// var user = document.getElementsByName("user")[0]; var pwd = document.getElementsByName("pwd")[0]; console.log(user.value,pwd.value); </script> </body> </html>
2,间接查找
parentNode // 父节点 childNodes // 所有子节点 firstChild // 第一个子节点 lastChild // 最后一个子节点 nextSibling // 下一个兄弟节点 previousSibling // 上一个兄弟节点 parentElement // 父节点标签元素 children // 所有子标签 firstElementChild // 第一个子标签元素 lastElementChild // 最后一个子标签元素 nextElementtSibling // 下一个兄弟标签元素 previousElementSibling // 上一个兄弟标签元素
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div> 123 <div class="c1">儿子</div> <div class="c1" id="i1"> <p>孙子</p> <div name="n1"> <span>二孙子</span> </div> <div name="n1">三孙子</div> </div> <div class="c1">二儿子</div> </div> <script> var il = document.getElementById("i1"); var pl_text = il.parentNode; var pl = il.parentElement; var eles_node = pl_text.childNodes; for (var j=0;j<eles_node.length;j++){ var current_node = eles_node[j]; if (current_node.nodeType==1){ console.log(eles_node[j]) } } var eles = pl.children; for(var i=0;i<eles.length;i++){ console.log(eles[i]); } </script> </body> </html>
二 操作:
1,内容:
innerText 获取文本 outerText innerHTML 获取标签、文本信息 value 值
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <a href="http://www.etiantian.org">老栓子<span>999</span></a> <input id="txt" type="text"/> <select> <option value="1">山西</option> <option value="2">北京</option> </select> <script> var obj = document.getElementsByTagName("a")[0]; // alert(obj.innerText); 获取文本 // alert(obj.innerHTML) 获取标签、文本信息 var val = document.getElementById("txt").value; 获取值 console.log(val); obj.innerText = "123"; obj.innerHTML = "<p>123</p>"; </script> </body> </html>
2,属性:
attributes // 获取所有标签属性 setAttribute(key,value) // 设置标签属性 getAttribute(key) // 获取指定标签属性
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div> <input type="button" value="全选" onclick="cheakall();"/> <input type="button" value="取消" onclick="cancleall();"> <input type="button" value="反选" onclick="reverseall();"> </div> <table> <thead> <tr> <th>序号</th> <th>用户名</th> <th>年龄</th> </tr> </thead> <tbody id="tb"> <tr> <td><input class="c1" type="checkbox"/></td> <td>开心</td> <td>20</td> </tr> <tr> <td><input class="c1" type="checkbox"/></td> <td>黑蛋</td> <td>20</td> </tr> <tr> <td><input class="c1" type="checkbox"/></td> <td>狗剩</td> <td>20</td> </tr> </tbody> </table> <script> function cheakall(){ var tb = document.getElementById('tb'); var checks = tb.getElementsByClassName("c1"); for (var i=0;i<checks.length;i++){ var current_check = checks[i]; current_check.checked = true; } } function cancleall(){ var tb = document.getElementById('tb'); var checks = tb.getElementsByClassName("c1"); for (var i=0;i<checks.length;i++){ var current_check = checks[i]; current_check.checked = false; } } function reverseall(){ var tb = document.getElementById('tb'); var checks = tb.getElementsByClassName("c1"); for (var i=0;i<checks.length;i++){ var current_check = checks[i]; if(current_check.checked){ current_check.checked = false; }else { current_check.checked=true; } } } </script> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title id="2">Title</title> </head> <body> <div> <h2>ok</h2> <form action="#" id="1" class="form1" name="form1"> <input id =5 type="text"> <input type="text"> <p>男:<input id=3 type="checkbox" name="男" value="nan"></p> <input type="submit"> </form> <h1 id="h1">hao</h1> <input type="datetime-local"> </div> <script> var names = document.getElementById('5'); //得到一个普通对象 names.id = 'newid'; //修改设置新标签属性ID names.className = "form"; //设置或修改标签css names.style.fontSize = '20px'; //设置标签样式 names.setAttribute('txt','mydefine'); //添加新属性 names.setAttribute('txt','mydefine'); //添加新属性,存在则忽略不报错 names.removeAttribute('txt'); //移除属性 names = names.getAttribute('id'); //获取属性值 console.log(names); </script> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> ul{ list-style: none; padding: 0; margin: 0; } ul li{ float: left; background-color: #2459a2; color: white; padding: 8px 10px; } .clearfix:after{ display: block; content: '.'; height: 0; visibility: hidden; clear: both; } .hide{ display: none; } .tab-menu .title{ background-color: #dddddd; } .tab-menu .title .active{ background-color: white; color: black; } .tab-menu .content{ border: 1px solid #dddddd; min-height: 150px; } </style> </head> <body> <div style=" 400px;margin: 0 auto"> <div class="tab-menu"> <div class="title clearfix"> <ul> <li target="h1" class="active" onclick="Shou(this);">价格趋势</li> <li target="h2" onclick="Shou(this);">市场分布</li> <li target="h3" onclick="Shou(this);">其他</li> </ul> </div> <div id="content"class="content"> <div con="h1">content1</div> <div con="h2" class="hide">content2</div> <div con="h3" class="hide">content3</div> </div> </div> </div> <script> function Shou(thr){ var target = thr.getAttribute("target"); thr.className="active"; var brother=thr.parentElement.children; for (var i=0;i<brother.length;i++){ if(thr ==brother[i]){ }else { brother[i].removeAttribute('class'); } } var contents =document.getElementById('content').children; for(var j=0;j<contents.length;j++){ var courent_content = contents[j]; var con =courent_content.getAttribute('con'); if (con==target){ courent_content.classList.remove("hide"); }else { courent_content.className='hide'; } } } </script> </body> </html>
3,class 操作:
className // 获取所有类名 以字符串的形式 classList.remove(cls) // 删除指定类 以列表的形式 classList.add(cls) // 添加类
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .hide{ display: none; } .c1{ position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,.5); z-index: 2; } .c2{ position: fixed; 400px; height: 300px; background: white; top: 50%; left: 50%; z-index: 3; margin-top: -150px; margin-left: -200px; } </style> </head> <body> <div> <input type="button"value="点我"onclick="Shou()"/> <input type="button"value="点我"onclick="Shou()"/> </div> <div id="shade" class="c1 hide"></div> <div id="modal" class="c2 hide"> <p>用户:<input type="text"/></p> <p>密码:<input type="password"></p> <p> <input type="button" value="确定" onclick="Hide();"> <input type="button" value="取消" onclick="Hide();"> </p> </div> <script> function Shou(){ document.getElementById('shade').classList.remove("hide"); document.getElementById('modal').classList.remove("hide"); } function Hide(){ document.getElementById('shade').classList.add("hide"); document.getElementById('modal').classList.add("hide"); } </script> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> ul{ padding: 0; margin: 0; } .hide{ display: none; } .menu{ 200px; height: 500px; background-color: #2459a2; border: 2px solid #333; } .menu .title{ background-color: brown; cursor: pointer; } .menu .content{ background-color: white; } </style> </head> <body> <div class="menu"> <div class="item"> <div class="title" onclick="Show(this);">菜单一</div> <div class="content"> <ul> <li>内容1</li> <li>内容1</li> <li>内容1</li> </ul> </div> </div> <div class="item"> <!--arg.下一个标签nex--> <div class="title" onclick="Show(this);">菜单二</div> <div class="content hide"> <ul> <li>内容2</li> <li>内容2</li> <li>内容2</li> </ul> </div> </div> <div class="item"> <div class="title" onclick="Show(this);">菜单三</div> <div class="content hide"> <ul> <li>内容3</li> <li>内容3</li> <li>内容3</li> </ul> </div> </div> <div class="item"> <div class="title" onclick="Show(this);">菜单四</div> <div class="content hide"> <ul> <li>内容4</li> <li>内容4</li> <li>内容4</li> </ul> </div> </div> </div> <script> function Show(arg){ arg.nextElementSibling.classList.remove('hide'); var father = arg.parentElement; var sons = father.parentElement.children; for(var i= 0;i<sons.length;i++){ var current_ele = sons[i]; if(current_ele == father){ }else { current_ele.children[1].classList.add('hide'); } } } </script> </body> </html>
4:标签操作:
var tag = document.createElement('li'); 创建标签 tag.innerText= val; var temp = document.createElement('a'); 创建标签 temp.innerText="百度"; temp.href = "http://etiantian.org"; tag.appendChild(temp);
操作标签:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div> <input type="text"/> <input type="button"value="添加" onclick="Shou(this);"/> </div> <div> <ul id="conmmentlist"> <li>凯欣</li> <li>大龙</li> <li>大虎</li> </ul> </div> <script> function Shou(the){ var val = the.previousElementSibling.value; // 获取输入的值 the.propertyIsEnumerable.value=""; var conmmentlist=document.getElementById("conmmentlist"); // 第一种方式 创建字符串 var str = "<li>" + val +"</li>"; // beforeBegin, 外部上边 // afterBegin, 内部必填神 // beforeEnd, 内部最后 // afterEnd 外部贴墙 conmmentlist.insertAdjacentHTML("beforeEnd",str); </script> </body> </html>
实例:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div> <input type="text"/> <input type="button"value="添加" onclick="Shou(this);"/> </div> <div> <ul id="conmmentlist"> <li>凯欣</li> <li>大龙</li> <li>大虎</li> </ul> </div> <script> function Shou(the){ var val = the.previousElementSibling.value; // 获取输入的值 the.propertyIsEnumerable.value=""; var conmmentlist=document.getElementById("conmmentlist"); // 第一种方式 创建字符串 var str = "<li>" + val +"</li>"; // beforeBegin, 外部上边 // afterBegin, 内部必填神 // beforeEnd, 内部最后 // afterEnd 外部贴墙 // conmmentlist.insertAdjacentHTML("beforeEnd",str); // 第二种方式,元素的方式 var tag = document.createElement('li'); 创建标签 tag.innerText= val; var temp = document.createElement('a'); 创建标签 temp.innerText="百度"; temp.href = "http://etiantian.org"; tag.appendChild(temp); // conmmentlist.appendChild(tag); conmmentlist.insertBefore(tag,conmmentlist.children[1]); } </script> </body> </html>
5、样式操作
利用javascript可以轻松的控制页面上的样式,就算没有样式表,也可以通过javascript控制页面声的任何元素的样式。
通过修改style对象的属性,可以修改任何一个对象的样式。首先我们就是要查找到要修改样式的对象,可以预先在对象中定义ID属性,然后由getElementById()方法查找到该对象。比如:
<h1 id=”head1”>This is Text</h1>
Document.getElementById(“head1”).style.color=red;
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .gg{ color: #666666; } .bb{ color: black; } </style> </head> <body> <input type="text" placeholder="请输入内容"/> <input type="text" class="gg" value="请输入内容" onfocus="fuu(this);"onblur="fxx(this);"/> <script> function fuu(ttt){ ttt.className='bb'; var curr_val = ttt.value; if(curr_val =="请输入内容"){ ttt.value = ""; } } function fxx(ttt){ var curr_val = ttt.value; if (curr_val =="请输入内容"|| curr_val.trim().length==0){ ttt.value = "请输入内容"; ttt.className = "gg"; } } </script> </body> </html>
6,位置操作:
总文档高度 document.documentElement.offsetHeight 当前文档占屏幕高度 document.documentElement.clientHeight 自身高度 tag.offsetHeight 距离上级定位高度 tag.offsetTop 父定位标签 tag.offsetParent 滚动高度 tag.scrollTop
/*
clientHeight -> 可见区域:height + padding
clientTop -> border高度
offsetHeight -> 可见区域:height + padding + border
offsetTop -> 上级定位标签的高度
scrollHeight -> 全文高:height + padding
scrollTop -> 滚动高度
特别的:
document.documentElement代指文档根节点
*/
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> body{ margin: 0; background-color: #dddddd; } .w{ margin: 0 auto; 980px; } .pg-header{ background-color: black; color: white; height: 48px; } .pg-body .menu{ position: absolute; left: 200px; 180px; background-color: white; float: left; } .pg-body .menu .active{ background-color: #425a66; color: white; } .pg-body .fixed{ position: fixed; top: 10px; } .pg-body .content{ position: absolute; left: 385px; right: 200px; background-color: white; float: left; } .pg-body .content .item{ height: 900px; } </style> </head> <body onscroll="Hua();"> <div class="pg-header"> <div class="w"> </div> </div> <div class="pg-body"> <div id="menu" class="menu"> <ul> <li>第一章</li> <li>第二章</li> <li>第三章</li> </ul> </div> <div id="content" class="content"> <div class="item">床前明月管</div> <div class="item">疑是地上霜</div> <div class="item">我是郭德纲</div> </div> </div> <script> function Hua(){ var huahua = document.body.scrollTop; var caiDan = document.getElementById('menu'); if(huahua>48){ caiDan.classList.add("fixed"); }else { caiDan.classList.remove("fixed"); } var items = document.getElementById("content").children; for (var i=0;i<items.length;i++) { var currentTiem = items[i]; var currentTiemBodyTop = currentTiem.offsetTop + currentTiem.offsetParent.offsetTop; var currentTtemWindowTop = currentTiemBodyTop - huahua; console.log(currentTtemWindowTop); if (currentTtemWindowTop<0){ caiDan.getElementsByTagName('li')[i].className = 'active'; } break } } // var currenthHeight = currentTiem.offsetHeight; // var bottomHeight = currentTiemBodyTop + currenthHeight; // // if (currentTtemWindowTop < 0 && huahua < bottomHeight) { // var ziJi = caiDan.getElementsByTagName('li')[i]; // ziJi.className = "active"; // var lis = caiDan.getElementsByTagName('li'); // for(var j = 0;j<lis.length;j++){ // if (ziJi == lis[j]){ // // }else { // lis[j].classList.remove('active'); // } // } // }break; // } // } </script> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div style="height: 20px;background-color: green;"></div> <div style="border: 5px solid pink;padding: 10px;"> <div> <div id="xo" style="height: 200px;overflow: auto; 400px;margin: 0 auto;border: 15px solid red;padding: 3px;" > <div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div> <div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div><div>sdf</div> <div>sdf</div> <div>sdf</div> <div>sdf</div> <div>sdf</div> </div> </div> </div> <script> var ii = document.getElementById("xo"); console.log(ii.scrollTop,"scrollTop"); console.log(ii.scrollHeight,"scrollHeight"); console.log(ii.clientTop,"clientTop"); console.log(ii.clientHeight,"clientHeight"); console.log(ii.offsetTop,"offsetTop"); console.log(ii.offsetHeight,"offsetHeight"); </script> </body> </html>
7、提交表单
document.geElementById('form').submit()
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form id="fom" action="https://www/sogou.com/web?" method="get"> <input name="query" type="text"/> <input type="button" onclick="SubmitForim();" value="提交"/> </form> <hr /> <input type="button" value="confirm" onclick="Firm();"/> <input type="button" value="Interval" onclick="Interval();"/> <input type="button" value="StopInterval" onclick="StopInterval();"/> <div> <input type="button" value="删除"onclick="Delete();"/> <input type="button" value="保留状态" onclick="UnDelete();"/> <div id="status"></div> </div> <script> function UnDelete(){ clearTimeout(t1); } function Delete(){ document.getElementById("status").innerText="已删除"; t1 = setTimeout(ClearStatus,5000); } function ClearStatus(){ document.getElementById("status").innerText=""; } function SubmitForim(){ document.getElementById('fom').submit(); } function Firm(){ var r =confirm('傻狍子'); console.log(r); } function f1(){ console.log(1234) } function Interval(){ si = setInterval(function(){ console.log(123); },1000); sii = setInterval(function(){ console.log(12); },2000); console.log(1) } function StopInterval(){ clearInterval(si); } </script> </body> </html>
8、其他操作
console.log 输出框 alert 弹出框 confirm 确认框 // URL和刷新 location.href 获取URL location.href = "url" 重定向 location.reload() 重新加载 // 定时器 setInterval 多次定时器 clearInterval 清除多次定时器 setTimeout 单次定时器 clearTimeout 清除单次定时器
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div id="btns"> <input type="button" value="点我1"/> <input type="button" value="点我2"/> <input type="button" value="点我3"/> </div> <script> function func(){ for(var i=0;i<3;i++){ var ret = (function func(arg){ console.log(arg) })(i); console.log(i); setInterval(ret,1000); } } 第一种方式 // var btns = document.getElementById("btns").children; // for(var j=0;j<btns.length;j++){ // var curront_inp = btns[j]; // curront_inp.onclick = function(){ // alert(j); // } // } 第二种方式 function func(){ for (var i=0;i<3;i++){ setInterval(function(){ console.log(i); },1000); } } func(); </script> </body> </html>
三、事件
对于事件需要注意的要点:
- this
- event
- 事件链以及跳出
this标签当前正在操作的标签,event封装了当前事件的内容。
实例:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <a href="http://etiantain.org" onclick="return func()">赖你 </a> <form action="请输入内容.html"> <div id="form1"> <input type="text"/> </div> <input type="submit" value="提交" onclick="return SubmitForim();"> </form> <script> function func(){ alert(123); return true; } function SubmitForim(){ var inputs = document.getElementById('form1').getElementsByTagName("input"); for (var i = 0;i<inputs.length;i++){ var currentInput = inputs[i]; var val = currentInput.value; if (val.trim().length==0){ alert("请输入内容"); return false; } } return true; </script> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .top{ background-color: brown; color:white; font-family: 华文隶书; font-size: 38px; text-align:center } </style> </head> <body> <div id="li" class="top">欢迎武sir莅临指导</div> <script> setInterval(function(){ dd = document.getElementById('li'); dd_text = dd.innerText; first_char = dd_text[0]; sub_char = dd_text.slice(1,dd_text.length); new_str = sub_char + first_char; dd.innerText = new_str; },1000); </script> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> ul{ padding: 0; margin: 0; } .hide{ display: none; } .menu{ 200px; height: 500px; background-color: #2459a2; border: 2px solid #333; } .menu .title{ background-color: brown; cursor: pointer; } .menu .content{ background-color: white; } </style> </head> <body> <div class="menu"> <div class="item"> <div class="title" onclick="Show(this);">菜单一</div> <div class="content"> <ul> <li>内容1</li> <li>内容1</li> <li>内容1</li> </ul> </div> </div> <div class="item"> <!--arg.下一个标签nex--> <div class="title" onclick="Show(this);">菜单二</div> <div class="content hide"> <ul> <li>内容2</li> <li>内容2</li> <li>内容2</li> </ul> </div> </div> <div class="item"> <div class="title" onclick="Show(this);">菜单三</div> <div class="content hide"> <ul> <li>内容3</li> <li>内容3</li> <li>内容3</li> </ul> </div> </div> <div class="item"> <div class="title" onclick="Show(this);">菜单四</div> <div class="content hide"> <ul> <li>内容4</li> <li>内容4</li> <li>内容4</li> </ul> </div> </div> </div> <script> function Show(arg){ arg.nextElementSibling.classList.remove('hide'); var father = arg.parentElement; var sons = father.parentElement.children; for(var i= 0;i<sons.length;i++){ var current_ele = sons[i]; if(current_ele == father){ }else { current_ele.children[1].classList.add('hide'); } } } </script> </body> </html>