JavaScript中DOM

概念

什么是DOM

 

1. 什么是 DOM


DOM 的全称是document object model 它的基本思想是将结构化文佳例如HTML xml解析成一系列的节点。就像一颗树一样。

所有的节点和最终的树结构,都有规范的对外接口,已使用编程语言的放大操作文档

 

2. 节点

DOM的最小组成单位叫做节点,节点组成一个文件的文档树

节点名称含义
Document 文档节点 整个文档(window.document)
DocumentType 文档类型节点 文档的类型
Element 元素节点 HTML 元素(比如<head>、<body>等)
Attribute 属性节点 HTML 元素的属性(比如 class="right")
Text 文本节点 HTML 文档中出现的文本
DocumentFragment 文档碎片节点 文档的片段

 

二、选取文档元素

1. 通过 ID 选取元素

<html>
<body>
<div id="my_div"></div>

<script>
    document.getElementById("my_div").style.height="100px";  // 设置 my_div 高度为 100px
    document.getElementById("my_div").style.background="red"; // 设置 my_div 颜色为 红色
</script>

</body>
</html>

 

2. 通过名字(Name)或标签名(TagName)选取元素

<html>
<body>
<input type="text" />
<input type="text" />

<script>
document.getElementsByTagName("input")[0].value="hello";   // 下标为 [0] 表示选取第 1 个 input 标签
document.getElementsByTagName("input")[1].value="shiyanlou"; // 下标为 [1] 表示选取第 2 个 input 标签
</script>

</body>
</html

 

三、节点、属性操作和文档遍历

1. 查询和设置元素的属性

<html>
<head>
<style>
.class_1 {
    height:100px;
    width:100px;
    background:red;
}
.class_2 {
    height:100px;
    width:100px;
    background:blue;
}
</style>
</head>

<body>
<div id="div_1" class="class_1"></div>
<br/>
<a>before:</a>

<script>
document.write(document.getElementById("div_1").getAttribute("class")); // 查询 div_1 的属性
</script>

<br/>
<a>after:</a>

<script>
document.getElementById("div_1").setAttribute("class","class_2");  // 修改 div_1 的属性为 class_2
document.write(document.getElementById("div_1").getAttribute("class")); // 再次查询 div_1 的属性
</script>

</body>

父节点

 

<html>
<body>
<div class="demo-parent">
    <div id="demo">        
    </div>
</div>

<script>
    document.write(document.getElementById("demo").parentNode.getAttribute("class"));
</script>
</body>
</html>

创建和插入节点

<html>
<body>
<div style="background:#00F; height:100px"></div>
<script>
    var mydiv = document.createElement("div");
    mydiv.style.height = "100px";
    mydiv.style.background = "red";
    document.getElementsByTagName("body")[0].appendChild(mydiv);
</script>
</body>
</html>

删除节点

<html>
<head>
<body>
<div>
    <div id="div_red" style="background:#F00; height:100px"></div>
    <div id="div_blue" style="background:#00F; height:100px"></div>
</div>
<script>
function remove_red(){
    var obj = document.getElementById("div_red");
    obj.parentNode.removeChild(obj);
    }
</script>
<button onclick="remove_red()">remove red div</button>
</body>
</html>

 

posted on 2017-03-29 17:13  王守昌  阅读(258)  评论(0编辑  收藏  举报

导航