前端三贱客 -- JavaScript中的DOM元素
文档对象模型(Document Object Model,DOM)是一种用于HTML编程接口。它给文档提供了一种结构化的表示方法,可以改变文档的内容和呈现方式。DOM相当于是一个模块,提供了关于HTML文档中对标签进行操作的功能,JavaScript结合DOM可以对HTML中的标签进行操作。可以把DOM看做是一张映射表,记录着一堆用代码操控document时的规章制度,直白点说,就是js操作html时的API。
DOM选择器
DOM中提供了一系列的选择器用于在HTML文档中找到指定的相关标签对象。
直接查找
document.getElementById(arg) // 根据ID获取一个标签对象 document.getElementsByClassName(arg) // 根据class属性获取标签对象集合 document.getElementsByName(arg) // 根据name属性值获取标签对象集合 document.getElementsByTagName(arg) // 根据标签名获取标签对象集合
示例一:
<!DOCTYPE html> <html> <head> <title>Dom Test</title> <style type="text/css"> .c1{ background-color: red; width: 400px; height: 200px; } .c2{ font-size: 20px; color: white; text-align: center; line-height: 200px; } </style> </head> <body> <input type="text" name="username" id="id1" size="20"><br> <input type="text" name="username" size="20"><br> <input type="text" name="username" size="20"><br> <div id="i2">this is a div</div> <a href="">111</a> <a href="">222</a> <div class="c1 c2">Hello Kugou!</div> <input type="button" onclick="func1()" value="点我getElementById"> <input type="button" onclick="func2()" value="点我getElementsByName"> <input type="button" onclick="func3()" value="点我change div value"> <input type="button" onclick="func4()" value="点我getElementsByTagName"> <input type="button" onclick="func5()" value="点我getElementsByClassName"> <script type="text/javascript"> function func1(){ var username_id = document.getElementById("id1"); console.log(username_id.value); alert(username_id.value); } function func2(){ var username = document.getElementsByName("username"); for(var i=0;i < username.length;i++){ console.log(username[i].value); alert(username[i].value) } } function func3(){ var x = document.getElementById("i2"); x.innerText="Hello Kugou!"; } function func4(){ /* body... */ var a_list=document.getElementsByTagName("a"); for (var i = 0;i<a_list.length;i++){ var var1 = a_list[i].innerText; a_list[i].innerText=var1 + "AAA"; } } function func5(){ var var_sty = document.getElementsByClassName("c1"); console.log(var_sty); var_sty[0].style.backgroundColor = ‘#00ff00‘; } </script> </body> </html>
间接查找
var tag = document.getElementById(arg); tag.parentElement // 找当前标签对象的父标签对象 tag.children // 找当前标签对象的所有子标签对象 tag.firstElementChild // 找当前标签对象的第一个子标签对象 tag.lastElementChild // 找当前标签对象最后一个子标签对象 tag.nextElementtSibling // 找当前标签对象下一个兄弟标签对象 tag.previousElementSibling // 找当前标签对象上一个兄弟标签对象
示例二:
<head> <title></title> <style type="text/css"> table { /* border: 1px solid; */ border-collapse: collapse; } table th, table td{ border: 1px solid; padding : 8px; } table th { font-weight: bold; } </style> </head> <body> <table> <thead> <tr> <th>主机ip</th> <th>端口号</th> <th>备注</th> <th>操作</th> </tr> </thead> <tbody> <tr> <td>1.1.1.1</td> <td>80</td> <td>web端口</td> <td><input type="button" value="删除" onclick="deleteRow(this)"></td> </tr> <tr> <td>2.2.2.2</td> <td>3306</td> <td>MySQL端口</td> <td><input type="button" value="删除" onclick="deleteRow(this)"></td> </tr> <tr> <td>2.2.2.2</td> <td>6379</td> <td>Redis端口</td> <td><input type="button" value="删除" onclick="deleteRow(this)"></td> </tr> </tbody> </table> <script type="text/javascript"> function deleteRow(self){ var rowTr = self.parentElement.parentElement; // alert(rowTr.value); rowTr.remove(); } </script>
DOM文本操作
对标签内部文本进行操作时,可以通过 innerText 和 innerHTML来进行。
innerText
标签对象.innerText,读取标签内容(仅文本)。
标签对象.innerText="武",修改标签内容(仅文本)。
innerHTML
标签对象.innerHTML,读取标签内容(含标签)。
标签对象.innerText="<a href=‘#‘>武</a>",修改标签内容(可标签、课文本)。
示例三
<!DOCTYPE html> <html> <head> <title></title> <style type="text/css"> table { border-collapse: collapse; } table th, table td{ border: 1px solid; padding: 8px; } table td{ font-size: 18px; } a{ text-decoration: none; } a:link {color:#FF0000;} /* 未被访问的链接 */ a:visited {color:#00FF00;} /* 已被访问的链接 */ a:hover {color:#FF00FF;} /* 鼠标指针移动到链接上 */ a:active {color:#0000FF;} /* 正在被点击的链接 */ </style> </head> <body> <table> <thead> <tr> <th>ID</th> <th>网站链接</th> <th>网站介绍</th> <th>读取</th> </tr> </thead> <tbody> <tr> <td>1</td> <td><a href="https://www.kugou.com">酷狗</a></td> <td>Hello Kugou 就是歌多</td> <td> <input type="button" name="" value="读取网站innerText" onclick="readSite(this)"> <input type="button" name="" value="读取完整innerHTML" onclick="readSummary(this)"> </td> </tr> </tbody> </table> <script type="text/javascript"> function readSite(self){ var inner_text_01 = self.parentElement.previousElementSibling.previousElementSibling; alert(inner_text_01.innerText); inner_text_01.innerText="百度"; var inner_text_02 = self.parentElement.previousElementSibling; alert(inner_text_02.innerText) inner_text_02.innerText=‘百度一下 你就知道‘ } function readSummary(self){ var inner_HTML = self.parentElement.previousElementSibling.previousElementSibling; alert(inner_HTML.innerHTML) inner_HTML.innerHTML="<a href=\"https://www.baidu.com\">百度</a>" } </script> </body> </html>
DOM值操作
文本框
<body> <input type="text" name="username" value="请输入用户名XXX" id="user"> <script type="text/javascript"> var username = document.getElementById("user") console.log("获取文本框值",username.value) username.value = "nuanhuang" console.log("更新文本框值",username.value) </script> </body>
多行文本框
<h3>个人简介</h3> <textarea id="article" cols="30" rows="10">不以物喜,不以己悲,先天下之忧而忧,后天下之乐而乐 </textarea><br> <input type="button" value="获取" onclick="get()"> <input type="button" value="更新" onclick="update()"> <script type="text/javascript"> function get() { // body... var contents = document.getElementById("article") alert(contents.value) } function update() { var contents = document.getElementById("article") contents.value = "瞎扯淡" } </script>
下拉框
<h3>居住地</h3> <select id="city" > <option value="0">北京</option> <option value="1">上海</option> <option value="2" selected="selected">广州</option> <option value="3">深圳</option> </select> <input type="button" value="获取居住地" onclick="getCity()"> <input type="button" value="更新" onclick="updateCity()"> <script type="text/javascript"> function getCity() { // body... var city = document.getElementById("city") switch (city.value) { case "0": alert(‘北京‘) break; case "1": alert(‘上海‘) break; case "2": alert(‘广州‘) break; case "3": alert(‘深圳‘) break; default: // statements_def alert(‘未知城市‘) break; } } function updateCity() { var city = document.getElementById("city") city.value = 0 } </script>
单选框
<h3>性别</h3> <input type="radio" name="gender" checked="checked" value=0>男 <input type="radio" name="gender" value=1>女 <br> <input type="button" value="显示值" onclick="getGender()"> <input type="button" value="更新值" onclick="updateGender()"> <script type="text/javascript"> function getGender(){ var gender = document.getElementsByName("gender") for(var i = 0;i < gender.length;i++){ if(gender[i].checked){ alert(gender[i].value); } } } function updateGender(){ var gender = document.getElementsByName("gender") for(var i = 0;i < gender.length;i++){ if(gender[i].value == "1"){ alert(‘xxx‘) gender[i].checked = true; } } } </script>
复选框
<h3>爱好</h3> <input type="checkbox" class="favi" value="0">篮球 <input type="checkbox" class="favi" value="1">足球 <input type="checkbox" class="favi" value="2">羽毛球 <input type="checkbox" class="favi" value="3">乒乓球 <br> <input type="button" value="显示值" onclick="getFavi()"> <input type="button" value="反选" onclick="updateFavi()"> <script type="text/javascript"> function getFavi(){ var valueList = [] var faviList = document.getElementsByClassName("favi") for(var i=0;i<faviList.length;i++){ if(faviList[i].checked){ valueList.push(faviList[i].value) } } console.log(valueList) alert(valueList) } function updateFavi(){ var faviList = document.getElementsByClassName("favi") for(var i=0;i<faviList.length;i++){ if(faviList[i].checked){ faviList[i].checked = false; }else { faviList[i].checked = true; } } } </script>
表格
<table> <thead> <tr> <th>选择</th> <th>姓名</th> <th>年龄</th> </tr> </thead> <tbody id="tb"> <tr> <td><input type="checkbox" value="0"></td> <td>李白</td> <td>18</td> </tr> <tr> <td><input type="checkbox" value="1"></td> <td>杜甫</td> <td>20</td> </tr> <tr> <td><input type="checkbox" value="2"></td> <td>王维</td> <td>21</td> </tr> </tbody> </table><br> <input type="button" value="全选" onclick="checkAll()"> <input type="button" value="取消" onclick="cancelAll()"> <input type="button" value="反选" onclick="checkReverse()"> <script type="text/javascript"> function checkAll(){ var trResList = document.getElementById("tb").children; for(var i = 0;i< trResList.length;i++){ var trTag = trResList[i]; trTag.firstElementChild.firstElementChild.checked = true; } } function cancelAll(){ var trResList = document.getElementById("tb").children; for(var i = 0;i<trResList.length;i++){ var trTag = trResList[i]; trTag.firstElementChild.firstElementChild.checked = false; } } function checkReverse(){ // alert("xxx") var trResList = document.getElementById("tb").children; for(var i=0;i<trResList.length;i++){ var trTag = trResList[i]; var inputTagRes = trTag.firstElementChild.firstElementChild; if(inputTagRes.checked){ inputTagRes.checked = false; }else{ inputTagRes.checked = true; } } } </script>
View Code
CLASS属性
- 标签对象.className,class属性对应的值直接操作。
- 标签对象.classList.remove(cls),class属性对应值删除某个样式。
- 标签对象.classList.add(cls),class属性中添加样式。
示例三:
<!DOCTYPE html> <html> <head> <title></title> <style type="text/css"> body{ margin: 0 auto; } .header{ height: 38px; background-color: #499ef3; position: fixed;top:0;right:0;left:0; } .header .menu{ width: 960px; margin: 0 auto; height: 38px; /* background-color: red; */ } .header .menu .left_menu{ float: left; line-height: 38px; } .header .menu .left_menu img{ width: 38px; height: 38px; border-radius: 50%; } .header .menu .right_menu{ float: right; line-height: 38px; } .header .menu .right_menu a{ text-decoration: none; display: inline-block; line-height: 38px; padding: 0 3px; color: red; } .header .menu .right_menu a:hover{ background-color: #dddddd; } .content{ width: 960px; margin: auto; margin-top: 38px; word-wrap:break-word; word-break:break-all; overflow: hidden; } .content p{ word-wrap:break-word; word-break:break-all; overflow: hidden; } .zhezhao{ position: fixed;top: 0;right: 0;bottom: 0;left: 0; background-color: gray; opacity: 0.5; z-index: 1; } .login{ width: 500px; height: 300px; position: fixed; top: 50%; left: 50%; margin-left: -250px; margin-top: -150px; background-color: yellow; z-index: 2; } .login .input_sty{ text-align: center; margin-top: 100px; } .login .input_sty p{ display: inline; } .hide{ display: none; } </style> </head> <body> <div class="header"> <div class="menu"> <div class="left_menu"> <img src="https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=2563547461,1954620067&fm=26&gp=0.jpg"> </div> <div class="right_menu"> <a onclick="login()">登录</a> <a href="">注册</a> <a href="">收藏</a> </div> </div> </div> <div id="zhezhao_id" class="zhezhao hide"></div> <div id="login_id" class="login hide"> <div class="input_sty"> <p>用户名:</p><input type="text" name="" value="请输入用户名:"> <br><br> <p>密  码:</p><input type="password" name="" value=""> <br><br> <input type="button" name="" value="登录"> <input type="button" name="" value="重置"> <input type="button" name="" value="返回" onclick="goBack()"> </div> </div> <div class="content"> <p>dsfasfasadfasfasfasdfasdfasdfasdfasdfasdfsadfasfasfasadfasfasfasdfasdfasdfasdfasdfasdfsadfasfasfasadfasfasfasdfasdfasdfasdfasdfasdfsadfasdfasdfasdfasdfasdfasdfasdfsasdfasdfasdfasdfasdfasdf</p> </div> <script type="text/javascript"> function login(){ // alert("xxxx") document.getElementById("zhezhao_id").classList.remove("hide"); document.getElementById("login_id").classList.remove("hide"); } function goBack(){ document.getElementById("zhezhao_id").classList.add("hide"); document.getElementById("login_id").classList.add("hide"); } </script> </body> </html>View Code
Style样式操作
如果想要对样式操作的粒度更细一些,可以使用style样式操作,他比class属性对样式的操作粒度更细。
示例四:
更换标题颜色
<!DOCTYPE html> <html> <head> <title></title> <style type="text/css"> body {margin: 0 auto;} .header { height: 38px; background-color: #dde369; text-align: center; line-height: 38px; } </style> </head> <body> <div id="header-id" class="header">且行且歌,行稳致远。</div> <input type="button" name="" value="换肤" onclick="change()"> <script type="text/javascript"> function change() { // body... document.getElementById("header-id").style.backgroundColor = "#a1648d"; } </script> </body> </html>
示例五:
开关灯测试
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>JavaScript学习</title> <style type="text/css"> .body{ position: fixed; top: 0;left: 0;bottom: 0;right: 0; background-color: white; z-index: 1; } input{ position: fixed; top: 50%;right: 50%; width: 80px; height: 80px; background-color: #854243; z-index: 2; color: white; font-size: 20px; } </style> </head> <body> <div id="i1" class="body">开关灯测试</div> <div class="menu"> <input id="i2" type="button" onclick="guandeng()" name="" value="关灯"> </div> <script type="text/javascript"> function guandeng(){ if(document.getElementById("i1").style.backgroundColor != "gray"){ document.getElementById("i1").style.backgroundColor = "gray"; document.getElementById("i2").value="开灯"; document.getElementById("i2").style.backgroundColor = ‘#12ddaa‘; }else { document.getElementById("i1").style.backgroundColor = "white"; document.getElementById("i2").value="关灯"; document.getElementById("i2").style.backgroundColor = ‘#854243‘; } // text.innerText="xxxx"; } </script> </body> </html>
示例五:
点赞
<!DOCTYPE html> <html> <head> <title></title> <style type="text/css"> body{ margin: 0 auto; } .container{ width: 800px; height: 200px; border: 1px solid #dddddd; margin: auto; margin-top: 20px; } .container .title{ font-size: 20px; font-weight: bold; margin: 5px; } .container img{ margin: 5px; width: 120px; height: 120px; } .container .item{ font-size: 18px; margin-left: 5px; color: green; /* 指定鼠标的类型 */ cursor: pointer; position: relative; } </style> </head> <body> <div class="container"> <div class="title">hello kugou!</div> <div><img src="https://imgessl.kugou.com/custom/150/20200106/20200106143601439455.jpg"></div> <div class="item" onclick="doFavor(this)">点赞</div> </div> <div class="container"> <div class="title">就是歌多!</div> <div><img src="https://imgessl.kugou.com/custom/150/20200103/20200103091738993254.jpg"></div> <div class="item" onclick="doFavor(this)">点赞</div> </div> <script type="text/javascript"> function doFavor(self) { var plusTag = document.createElement(‘span‘); var fontSize = 10; var marginLeft = 10; var marginTop = 10; var opacity = 1; plusTag.innerText = "+1"; plusTag.style.color = ‘green‘; plusTag.style.position = ‘absolute‘; plusTag.style.fontSize = fontSize + ‘px‘; plusTag.style.marginLeft = marginLeft + ‘px‘; plusTag.style.marginTop = marginTop + ‘px‘; plusTag.style.opacity = opacity; self.appendChild(plusTag); var interval = setInterval(function () { fontSize += 3; marginLeft += 5; marginTop -= 5; opacity -= 0.2; plusTag.style.fontSize = fontSize + ‘px‘; plusTag.style.marginLeft = marginLeft + ‘px‘; plusTag.style.marginTop = marginTop + ‘px‘; plusTag.style.opacity = opacity; if (opacity <= 0) { self.removeChild(plusTag); clearInterval(interval); } }, 100) } </script> </body> </html>
事件
- onclick 单击时触发事件
- ondblclick 双击触发事件
- onchange 内容修改时触发事件
- onfocus 获取焦点时触发事件
- onblur 失去焦点触发事件
示例六:菜单栏
<!DOCTYPE html> <html> <head> <title></title> <style type="text/css"> body{ margin: auto; } .pg-header{ height: 38px; background-color: #499ef3; text-align: center; line-height: 38px; font-size: 28px; color: blue; font-weight: bold; } .menu{ position: fixed; width: 220px; left: 0;top: 38px;bottom: 0; /* background-color: gray; opacity: 0.5; */ overflow: scroll; } .content{ position: fixed; top: 38px;right: 0;bottom: 0;left: 220px; background-color: orange; overflow: scroll; } .menu .title{ height: 28px; background-color: #5f4687; color: white; line-height: 28px; font-size: 16px; padding: 8px; border-bottom: 1px solid #dddddd; /* border-right: 1px solid #dddddd; */ } .menu .child{ /* display: block; */ /* background-color: yellow; */ border-bottom: 1px solid #dddddd; } .menu .child a{ display: block; text-decoration: none; padding: 5px 10px; color: black; z-index: 10; } .menu .child a:hover{ background-color: #dddddd; } .hide { display: none; } </style> </head> <body> <div class="pg-header">东方好莱坞</div> <div class="menu"> <div class="title" onclick="showMenu(this)">国产电影</div> <div class="child"> <a href="#">我不是药神</a> <a href="#">我和我的祖国</a> <a href="#">中国机长</a> </div> <div class="title" onclick="showMenu(this)">日韩电影</div> <div class="child hide"> <a href="">我的野蛮女友</a> <a href="">素媛</a> <a href="">熔炉</a> </div> <div class="title" onclick="showMenu(this)">欧美电影</div> <div class="child hide"> <a href="">肖申克的救赎</a> <a href="">飞跃疯人院</a> <a href="">阿甘正传</a> </div> </div> <div class="content">xxxx</div> <script type="text/javascript"> function showMenu(self){ // body... var childList = document.getElementsByClassName(‘child‘); for(var i=0;i< childList.length;i++){ childList[i].classList.add("hide") } self.nextElementSibling.classList.remove(‘hide‘) } </script> </body> </html>
示例七:文本框
<!DOCTYPE html> <html> <head> <meta charset=‘utf-8‘/> <title>DOM</title> <style> .gray { color: gray; } .red { color: red; } </style> </head> <body> <input type=‘text‘ class=‘gray‘ value=‘请输入关键字‘ onfocus=‘getFocus(this);‘ onblur=‘leave(this);‘/> <script type="text/javascript"> function getFocus(self) { self.className = ‘red‘; if (self.value === ‘请输入关键字‘ || self.value.trim().length === 0) { self.value = ‘‘; } } function leave(self) { if (self.value.length === 0) { self.value = ‘请输入关键字‘; self.className = ‘gray‘; } else { self.className = ‘red‘; } } </script> </body> </html>
相关推荐
luvhl 2020-08-17
liaoxuewu 2020-07-08
liaoxuewu 2020-06-26
北京老苏 2020-06-25
Lophole 2020-06-14
SIMONDOMAIN 2020-06-14
luvhl 2020-06-13
SIMONDOMAIN 2020-05-31
hyMiss 2020-05-19
liaoxuewu 2020-05-19
书虫媛 2020-05-15
liaoxuewu 2020-05-11
liaoxuewu 2020-05-10
小仙儿 2020-05-09
hyMiss 2020-05-01
liaoxuewu 2020-04-29
星星有所不知 2020-10-12