document对象是BOM的一部分。同时也是HTML DOM的 HTMLDocument对象的一种表现形式
访问attribute的三个方法。
getAttribute
Retrieves the value of the specified attribute.
Syntax
vAttribute = object.getAttribute(sAttrName)
setAttribute
Sets the value of the specified attribute.
Syntax
object.setAttribute(sAttrName, vAttrValue)
removeAttribute
Removes the specified attribute from the object.
Syntax
object.removeAttribute(sAttrName)
然而在HTML DOM中可以直接用同样名称的属性来获取和设置这些值
<div id="Div2">2</div>
<p id="p1" class="header">Hello World!</p>
alert(div1.getAttribute("id")); //output "p1" DOM表示
alert(div1.id ); //outputs "p1" HTML DOM 表示
div1.setAttribute("myAtt","myAttributes");
alert("myAttributes : " + div1.getAttribute("myAtt")); //outputs myAttributes
alert(div1.getAttribute("class")); //outputs "header"
alert(div1.className); //outputs "header"
创建和操作节点
DOM Document(文档)中的一些方法用于创建不同的节点, 最常用到的方法是
createDocumentFragment() 创建文档随片节点
createElement(tagName) 创建标签为(tagName)的元素
createTextNode(text) 创建包含文本text的文本节点
createComment 基本上没什么用
注意:
所有的DOM操作必须在页面完全载入之后才能进行,当页面正在载入时,要向DOM插入相关代码是不可能的 ,因为在页面完全下载到Client之前,是无法完全构建DOM树.所以,必须使用onload事件句柄来执行代码
{
//添加一个 <p>Hello World2!</p>
//创建p元素
var oP = document.createElement("p");
//创建text文本
var oText =document.createTextNode("Hello World2!");
//利用appendChild将文本对象添加到oP对象的childNodes的结尾
oP.appendChild(oText);
document.body.appendChild(oP);
alert('添加成功');
//替换节点
var oNewP = document.createElement("p");
var oNewText =document.createTextNode("Replace Hello World");
var oOldP =document.getElementsByTagName("p")[0];
oNewP.appendChild(oNewText);
//最好用parentNode来定位
//document.body.replaceChild(oNewP,oOldP);
oOldP.parentNode.replaceChild(oNewP,oOldP);
alert('替换成功');
//删除节点最好用parentNode来定位.确保访问的是它真正的父节点.
var op1=document.getElementsByTagName("p");
op1[0].parentNode.removeChild(op1[0]);
alert('删除成功');
}
</body>
大部分情况下,HTML DOM元素中包含的所有特性都是可作为属性。
oImg.getAttribute("src") == oImg.src
oImg.getAttribute("border") == oImg.border
前者是DOM的属性和方法 ,后者是HTML DOM的属性和方法。
绝大部分HTML DOM元素中包含的所有特性都是可作为属性的,特例是class特性,因为class在 ECMAScript中是一个保留关键字,在JavaScript中,它不能用作变量名,属性或者函数名,所以响应的属性名就变成className
浙公网安备 33010602011771号