6.25随笔

1.nodeList

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<p>您好</p>
<p>你好</p>
<p>您好</p>
<p>你好</p>
</body>
<script>
var x = document.getElementsByTagName("p");
for (var i=0;i<x.length;i++){
}
var y = x[2];
console.log(y)      //hello
</script>
</html>

2.firstChild以及lastChild

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<ul id="box">
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
</body>
<script type="text/javascript">
var box = document.getElementById('box');
var node1 = box.firstChild.nodeName;     //#text
var node2 = box.lastChild.nodeName;     //#text
alert(node1);
alert(node2);
</script>
</html>

3.previousSibling

previousSibling 属性返回同一树层级中指定节点的前一个节点。

被返回的节点以 Node 对象的形式返回。

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<ul id="box"><li id="lis1">1</li><li id="lis2">2</li></ul>    
</body>
<script type="text/javascript">
var lis2 = document.getElementById('lis2');
var damo = lis2.previousSibling.id;    //前一个id lis1 li之间有空格的返回的则是undefined
alert(damo);
</script>
</html>

4.appendChild

在列表中添加项目

appendChild() 方法向节点添加最后一个子节点。

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<ul id="box">
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
</body>
<script type="text/javascript">
var node = document.createElement("LI");    //创建元素节点
var textnode = document.createTextNode("4");    //创建文本节点
node.appendChild(textnode);
document.getElementById("box").appendChild(node);
</script>
</html>

5.insertBefore

insertBefore() 方法在您指定的已有子节点之前插入新的子节点。

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<ul id="box">
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
</body>
<script>
var newItem=document.createElement("LI"); //创建元素节点
var textnode=document.createTextNode("1"); //创建文本节点
newItem.appendChild(textnode); //添加文本节点
var box=document.getElementById("box"); //获取元素
box.insertBefore(newItem,box.childNodes[0]); //添加到位置
</script>
</html>

6.previousElementSibling

前一个兄弟元素。

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<ul id="box"><li id="lis1">1</li><li id="lis2">2</li></ul>
</body>
<script type="text/javascript">
var lis2 = document.getElementById('lis2');
var damo = lis2.previousElementSibling.id;    //返回的是前一个兄弟元素   lis1
alert(damo);
</script>
</html>

7.parentNode

parentNode 属性常被用来改变文档的结构。

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="box">
hello
</div>
</body>
<script type="text/javascript">
var box = document.getElementById("box");
box.parentNode.removeChild(box);   //删除
</script>
</html>

posted @ 2017-06-25 20:20  云随风走  阅读(89)  评论(0编辑  收藏  举报