定位:
var a = document.getElementByIt( "id" )
同辈元素
var b = a.nextSibling; -- 找 a 的下一个同辈元素,
var b = a.previousSibling; -- 找 a 的上一个同辈元素,
<html > <head> <title></title> <style type ="text/css"> .div1{ width:100px; height:100px; background-color:red; margin-right:10px; font-size:35px; color:white; float:left ; } </style> </head> <body> <div class="div1">1</div><div class="div1" id="div2">2</div><div class="div1">3</div> </body> </html> <script type="text/javascript" > var odiv2 = document.getElementById("div2"); odiv2.onclick = function () { alert(odiv2.previousSibling.innerText); } </script>
-- 当三个 div 写在一行时 2 的上一个是 1,下一个是3.
中间隔一个取上一个
odiv2.previousSibling.previousSibling.innerText
空格和换行也算一个元素,不管多少空格都算一个,不管多少换行都算一个
<html > <head> <title></title> <style type="text/css"> .div1 { width: 100px; height: 100px; background-color: red; margin-right: 10px; font-size: 35px; color: white; float: left; } </style> </head> <body> <div class="div1">1</div> <div class="div1" id="div2">2</div> <div class="div1">3</div> <div class="div1">4</div> </body> </html> <script type="text/javascript"> var odiv2 = document.getElementById("div2"); odiv2.onclick = function () { alert(odiv2.nextSibling.nextSibling.nextSibling.nextSibling.innerText); } </script>
-- 获取 4 的内容
例
制作一个下拉菜单(仿qq)
<html > <head> <title></title> <style type="text/css"> .div1 { width: 100px; height: 30px; border: 2px solid black; margin-top: 2px; background-color: blue; text-align: center; line-height: 30px; } .div2 { width: 100px; height: 150px; border: 2px solid black; display: none; -- 隐藏菜单不留位置 } </style> </head> <body> <div class="div1">好友</div> <div class="div2"></div> <div class="div1">家人</div> <div class="div2"></div> <div class="div1">同学</div> <div class="div2"></div> <div class="div1">二货</div> <div class="div2"></div> <div class="div1">陌生人</div> <div class="div2"></div> </body> </html> <script type="text/javascript"> var odiv1 = document.getElementsByClassName("div1"); for (var i = 0; i < odiv1.length; i++) { odiv1[i].onclick = function () { //关上下拉菜单 if (this.nextSibling.nextSibling.style.display != "none") { this.nextSibling.nextSibling.style.display = "none"; } else { for (var j = 0; j < odiv1.length; j++) { //一次只能打开一个下拉菜单 odiv1[j].nextSibling.nextSibling.style.display = "none" } this.nextSibling.nextSibling.style.display = "block" } //打开下拉菜单 } } </script>
效果图
本次练习出现的问题
** 注意字母的大小写
** 注意 id 定位与 class 定位
** 主要返回的是一个数组
** 用 this 表示这次执行,
父级 子集元素
var b = a.parentNodes; -- 找 a 的上一级父级元素
var b = a.childNodes; -- 找出 a 的下一级子元素, 是一个数组
<div id="a">
<div id="b">
<div id="c"></div>
</div>
</div>
b 的父级只有一个 a ,b 的子级有 3 个 c 是第二个。
var b = a.childNodes; -- 第一个子元素
var b = a.lastChild; -- 最后一个
var b = a.childNodes[ n ] -- 找第几个
alert( nodes)[ i ] instanceof Text ); -- 判断是不是文本,是 true 不是 flase。
var obj = document.createElement( "标签名" )
-- 动态创建一个 Dom对象,创建一个元素。
a.appendChild( obj ) -- 向 a 中添加一个元素 ,添加在末尾
a.removeChild( obj ) -- 删除一个子元素。