layout: post
title: "JS进阶之DOM"
date: 2016-05-31 13:28:27 +0800
comments: true
categories: [JavaScript]
这段时间开始实习,拿到手一个项目。都没什么时间写博客了,在写这个项目的实际过程中,发现对JS还是很陌生了。所以决定在空余时间提升下JS。在过了一遍基本的之后看到DOM的时候发现这个东西不太好懂,就觉得写个博文。
认识DOM
文档对象模型DOM(Document Object Model)定义访问和处理HTML文档的标准方法。DOM 将HTML文档呈现为带有元素、属性和文本的树结构(节点树)。
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>style样式</title>
</head>
<body>
<h2 id="con">I love JavaScript</H2>
<p> JavaScript使网页显示动态效果并实现与用户交互功能。</p>
<script type="text/javascript">
var myh2=document.getElementById("con");
myh2.style.color="red";
myh2.style.backgroundColor="#CCC";
myh2.style.display="none";
</script>
</body>
</html>
将HTML代码分解为DOM节点层次图:

HTML文档可以说由节点构成的集合,DOM节点有:
-
元素节点: 上图中
<html>、<body>、<p>
等都是元素节点,即标签。 -
文本节点:向用户展示的内容,如
<li>...</li>
中的JavaScript、DOM、CSS等文本。 -
属性节点:元素属性,如
<a>
标签的链接属性href="http://www.imooc.com"
。
节点属性:

遍历节点树:

以上图ul为例,它的父级节点body,它的子节点3个li,它的兄弟结点h2、P。
DOM操作:

节点属性
在文档对象模型 (DOM) 中,每个节点都是一个对象。DOM 节点有三个重要的属性 :
- nodeName : 节点的名称
- nodeValue :节点的值
- nodeType :节点的类型
**nodeName 属性: **节点的名称,是只读的。
- 元素节点的 nodeName 与标签名相同
- 属性节点的 nodeName 是属性的名称
- 文本节点的 nodeName 永远是 #text
- 文档节点的 nodeName 永远是 #document
nodeValue 属性:节点的值
- 元素节点的 nodeValue 是 undefined 或 null
- 文本节点的 nodeValue 是文本自身
- 属性节点的 nodeValue 是属性的值
nodeType 属性:节点的类型,是只读的。以下常用的几种结点类型:
元素类型 | 节点类型 |
---|---|
元素 | 1 |
属性 | 2 |
文本 | 3 |
注释 | 8 |
文档 | 9 |
网友评论