javascript - DOM对象控制HTML元素详解
1.方法
getAttribute() --获取元素属性 setAttribute() --设置元素属性 childNodes() --访问子节点 parentNodes() --访问父节点 createElement() --创建元素节点 createTextNode --创建文本节点 insertBefore() --插入节点 removeChild() --删除节点 offsetHeight --返回,任何一个元素的高度包括边框和填充,但不是边距 scrollHeight --返回整个元素的高度(包括带滚动条的隐蔽的地方) |
getElementsByName() -- 获取name
123456789<script>functiongetName() {varcount = document.getElementsByName("pn");alert(count.length);//count.length = 3varp = count[2];p.innerHTML ="World";}getName();</script>
getAttribute() --获取元素属性
123456<a id="aid"title="得到了a标签的属性"></a>functiongetAttr() {varanode = document.getElementById("aid");varattr = anode.getAttribute("title");alert(attr);}
childNodes() --访问子节点
123456789 <ul> <li>1</li> <li>2</li> <li>3</li></ul>function getChildNode() { var childnode = document.getElementsByTagName("ul")[0].childNodes; alert("length:" + childnode.length + ",nodeName:" + childnode[0].nodeName); }

createElement() --创建元素节点
123456789<ul><li>1</li><li>2</li><li>3</li></ul>functiongetChildNode() {varchildnode = document.getElementsByTagName("ul")[0].childNodes;alert("length:"+ childnode.length +",nodeName:"+ childnode[0].nodeName);}

|
1
2
3
4
5
6
7
8
|
function createNode() { var body = document.body; var input = document.createElement("input"); input.setAttribute("value", "按钮"); input.setAttribute("type", "button"); body.appendChild(input); } createNode(); |
insertBefore() --插入节点
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
<div id="div"> <p id="pid">这个第1个位置</p> </div> <script type="text/javascript"> function addNode() { var div = document.getElementById("div"); var pid = document.getElementById("pid"); var newnode = document.createElement("p"); newnode.innerHTML = "这个新增加的P"; div.insertBefore(newnode, pid); } addNode(); </script> |

浙公网安备 33010602011771号