《DOM Scripting》学习笔记-——第三章 DOM

2023-07-29,,

《Dom Scripting》学习笔记

第三章 DOM

本章内容:

1、节点的概念。

2、四个DOM方法:getElementById, getElementsByTagName, getAttribute, setAttribute

节点

  举例:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <meta http-equiv="content-type" content="text/html; ➥charset=utf-8" /> <title>Shopping list</title> </head> <body> <h1>What to buy</h1> <p title="a gentle reminder">Don’t forget to buy this stuff.</p> <ul id="purchases"> <li>A tin of beans</li> <li>Cheese</li> <li>Milk</li> </ul> </body> </html>

元素节点(element nodes): <body>, <p>, and <ul>

文本节点(text nodes): “Don’t forget to buy this stuff.

在XHTML文档中,文本节点总是包含在元素节点内部。但并非所有元素节点都包含文本节点。在上例中,<ul>元素没有直接包含任何文本节点,它包含的<li>元素节点包含着文本节点。

属性节点(attribute nodes): title="a  gentle  reminder"

因为属性总是被放在起始标签里,所以属性节点总是被包含在元素节点中。

getElementById:是与document对象相关联的函数。参数:想获得的那个元素的id(放在单引号或双括号中)。此函数会返回一个对象,该对象对应着拥有id的元素。

getElementByTagName:getElementByTagName()方法将返回一个对象数组,每个对象分别对应着文档里有着给定标签的一个元素。

getAttribute:查找元素属性的值。语法:object.getAttribute(attribute)。

当属性值不存在时,返回空或“null”(取决于浏览器)

var paras = document.getElementsByTagName("p");
for (var i=0; i< paras.length; i++)
{
var title_text = paras[i].getAttribute("title");
if (title_text) alert(title_text);
} //if (title_text)等价于if (title_text != null)

setAttribute:对属性的节点值作出修改。当属性不存在时,创建属性并赋值。属性存在时,修改属性的值。语法:object.setAttribute(attribute,value)。

var shopping = document.getElementById("purchases");
alert(shopping.getAttribute("title"));//弹出空白或“null”
shopping.setAttribute("title","a list of goods");
alert(shopping.getAttribute("title"));//弹出a list of goods

《DOM Scripting》学习笔记-——第三章 DOM的相关教程结束。

《《DOM Scripting》学习笔记-——第三章 DOM.doc》

下载本文的Word格式文档,以方便收藏与打印。