JavaScript DOM——“节点条理”的注重要点

几个观点:

  • DOM:文档对象模子,是针对 HTML 和 XML 文档的一个 API(应用程序编程接口)。

  • 根节点:就是 Document 节点。

  • nodeType: 一切节点的属性,用于表明节点的范例。

Node 范例

DOM1 级的接口,该接口除了 IE 以外,在其他一切浏览器中都能够接见到这个范例。

节点范例由在 Node 范例中定义的以下 12 个数值常量来示意,任何节点范例必居其一:

  1. Node.ELEMENT_NODE;

  2. Node.ATTRIBUTE_NODE;

  3. Node.TEXT_NODE;

  4. Node.CDATA_SECTION_NODE;

  5. Node.ENTITY_REFERENCE_NODE;

  6. Node.ENTITY_NODE;

  7. Node.PROCESSING_INSTRUCTION_NODE;

  8. Node.COMMENT_NODE;

  9. Node.DOCUMENT_NODE;

  10. Node.DOCUMENT_TYPE_NODE;

11. Node.DOCUMENT_FRAGMENT_NODE;
12. Node.NOTATION_NODE;

离别返回 1-12 数值。

如:

<h1 id="h1">hello this is h1</h1>
<h2 id="h2">hello this is h2</h2>
<p id="p">this is a paragraph<img id="img" alt="none......"></p>

console.log(document.getElementById("h1").nodeType == Node.ELEMENT_NODE); //true

因为 IE 兼容性题目,Node 范例的组织函数无效,最好照样将它换成数字值举行比较。如:

console.log(document.getElementById("h1").nodeType == 1); //true

nodeNamenodeValue属性

在运用这两个属性之前,最好是先检测一下节点的范例:

if (someNode.nodeValue == 1){
    value = someNode.nodeName;
}

<input id="input" type="text" name="textInput" value="this is an input">
console.log(document.getElementById("input").nodeName); //INPUT
console.log(document.getElementById("input").nodeValue); //null

关于元素节点(Node.ELEMENT_NODE),nodeName 中一直是元素的标署名,nodeValue 中则为 null。

节点关联

childNodes属性和NodeList对象和它的item()要领

  • 前者中保留着一个 NodeList 对象;

  • 后者并非 Array 的实例;

  • 能够经由过程方括号和 item() 要领来接见在后者的节点;

如:

<p id="p">this is a paragraph<img id="img" alt="none......"></p>

var para = document.getElementById("p");
var array = Array.prototype.slice.call(para.childNodes,0);
console.log(array);

上述代码在 IE8 中无效,因为 IE8 及更早版本将 NodeList 完成为一个 COM 对象。但下面的代码能够在一切浏览器中运转:

function convertToArray(nodes){
    var array = null;
    try{
        array = Array.prototype.slice.call(nodes,0);
    }catch(ex){
        array = new Array();
        for (var i=0; i<nodes.length; i++){
            array.push(nodes[i]);
        }
    }
    return array;
}

parentNode属性和previousSiblingnextSibling属性

parentNode属性指向文档树中的父节点;同胞节点中第一个节点的previousSibling属性的值为null;同理末了一个节点的nextSibling属性的值也为null。如:

if (someNode.nextSibling === null){
    console.log("last node in the parent's childNodes list.");
} else if(someNode.previousSibling === null){
    console.log("first node in the parent's childNodes list.");
}

firstChild属性和lastChild属性

这两个属性离别即是: someNode.childNodes[0]someNode.childNodes[someNode.childNodes.length - 1];

hasChildNodes()要领和ownerDocument属性

前者返回是不是包含子节点的布尔值;后者指向示意悉数文档的文档节点。

<h1 id="h1">hello this is h1</h1>

var title = document.getElementById("h1");
console.log(title.childNodes) //["hello this is h1"]

<h1 id="h1">hello this is h1</h1>
var title = document.getElementById("h1");
console.log(title.ownerDocument.nodeType) //9

操纵节点

以下述代码为例:

<p id="p">this is a paragraph<img id="img" alt="none......"></p>

appendChild()要领

该要领用于向 childNodes 列表的末端增加一个节点。个中,假如在 挪用 appendChild() 时传入了父节点的第一个子节点,那末该节点就会成为父节点的末了一个子节点,如:

var txt = document.getElementById("p");
txt.appendChild(txt.firstChild);
console.log(txt.childNodes) //[<img id="img" alt="none......">, "this is a paragraph"]

insertBefore()要领

用于把节点放在 childNodes 列表中某个特定的位置上。吸收两个参数:要插进去的节点和作为参照的节点,如:

var txt = document.getElementById("p");

var newNode = document.createElement("p");
var newNode_value = document.createTextNode("hello there");
newNode.appendChild(newNode_value);

txt.insertBefore(newNode, txt.lastChild);
document.write(Array.prototype.slice.call(txt.childNodes,0));//[object Text],[object HTMLParagraphElement],[object HTMLImageElement]

假如参照节点为 null,则 insertBefore() 与 appendChild() 实行雷同的操纵。

replaceChild()要领

该要领吸收两个参数:要插进去的节点和要替代的节点,如:

var txt = document.getElementById("p");

var newNode = document.createElement("p");
var newNode_value = document.createTextNode("hello there");
newNode.appendChild(newNode_value);

txt.replaceChild(newNode, txt.lastChild);
document.write(Array.prototype.slice.call(txt.childNodes,0));//[object Text],[object HTMLParagraphElement]

removeChild()要领

该要领吸收一个参数:要删除的节点,如:

var txt = document.getElementById("p");

txt.removeChild(txt.lastChild);
document.write(Array.prototype.slice.call(txt.childNodes,0));//[object Text]

其他要领

cloneNode()要领

该要领一切范例节点都具有;用于建立挪用这个要领的节点的一个完全雷同的副本。吸收一个参数,示意是不是实行深赋值。true 实行深复制,复制节点及悉数子节点树;false 实行浅复制,只复制节点自身,后要经由过程 appendChild() 等要领增加到文档中。如:

<ul id="unordered">
    <li>item 1</li>
    <li>item 2</li>
    <li>item 3</li>
</ul>

var myList = document.getElementById("unordered");
var deepList = myList.cloneNode(true);
console.log(deepList.childNodes.length); //7 (IE < 9 版本状况下为3,因为不会建立空白符节点。)

var shallowList = myList.cloneNode(false);
console.log(shallowList.childNodes.length); //0

normalize()要领

该要领的作用是处置惩罚文档树中的文本节点。在涌现文本节点不包含文本,或许衔接涌现两个文本节点的状况下,就删除它。

Document 范例

JavaScript 经由过程 Document 范例示意文档,在浏览器中,document 对象是 HTMLDocument 的一个实例,示意悉数 HTML 页面。Document 节点具有以下特征:

  1. console.log(document.nodeType + document.nodeName + document.nodeValue + document.parentNode + document.ownerDocument); //9#documentnullnullnull

  2. 以及其子节点多是一个 DocumentType(最多一个)、Element(最多一个)、ProcessingInstruction 或 Comment。

文档的子节点

documentElement属性和body属性

其子节点多是一个 DocumentType(最多一个)、Element(最多一个)、ProcessingInstruction 或 Comment。但另有两个内置的接见其子节点的体式格局:一个是 documentElement 属性,该属性一直指向 <html> 元素如:

var html = document.getElementsByTagName("html")[0];
console.log(document.documentElement === html); //true

var html = document.firstChild;
console.log(document.documentElement === html); //true

var html = document.childNodes[0];
console.log(document.documentElement === html); //true

以上代码建立在以下网页源代码之上:

<html>
    <head>
    </head>
    <body>
    <script>
        var html = document.childNodes[0];
        console.log(document.documentElement === html); //true
    
    </script>
    </body>
</html>

别的一个则是 body 属性。直接指向 <body> 元素。

DocumentTypedoctype属性

通常将 <!DOCTYPE> 标签算作一个与文档其他部份差别的实体,能够经由过程 doctype 属性(document.doctype)检察。如:

<!doctype html>
<html>
    <head>
    </head>
    <body>
    <script>
        console.log(document.doctype); //<!DOCTYPE html>    
    </script>
    </body>
</html>

浏览器对 document.doctype 的支撑差别很大,重要有:

  • IE8 及之前的版本:当作诠释,document.doctype 的值为 null;

  • IE9+ 及 Firefox:作为第一个子节点;

  • Safari、Chrome 和 Opera:不作为文档的子节点。

别的,按理说涌现在 html 标签以外的诠释也算是文档的子节点。如:

<!--第一个诠释-->
<html>
    <head>
    </head>
    <body>
    </body>
</html>
<!--第二个诠释-->

浏览器在处置惩罚位于 html 标签以外的诠释方面存在以下差别:

  • IE8 及之前的版本、Safari 3.1 及更高的版本、Opera 和 Chrome 只为第一条诠释建立节点;

  • IE9 及更高的版本将两个诠释都建立为节点;

  • Firefox、Safari 3.1 之前的版本会疏忽这两个诠释。

文档信息

title属性

document 对象的另一个属性是 title,包含这 title 元素中的文本,然则修正 title 属性的值并不会
转变 title 标签元素。如:

var x = setTimeout(setTitle, 1000);
function setTitle(){
    document.title = "Hello";
    var y = setTimeout(setTitle2, 1000);
    function setTitle2(){
        document.title = "World";
        x = setTimeout(setTitle, 1000);
    }
}

以上代码能够以1秒的速率自动切换显现 title 标签的内容

URLdomainreferrer属性

三者离别包含完全的 URL;页面的域名以及衔接到当前页面的谁人页面的 URL。三个属性当中只要 domain 是能够设置的。如:

//假定页面来自 p2p.wrox.com 域

document.domain = "wrox.com"; //胜利
document.domain = "baidu.com"; //失利

别的,因为跨域平安限定,来自差别的子域的页面没法经由过程 js 通讯。另有,假如域名一最先是“松懈的”(loose),那末就不能再设置为“紧绷的”(tight)。行将 document.domain 设置为”wrox.com”以后,就不能再将其设置回”p2p.wrox.com”不然将失足。

查找元素

getElementById()要领

该要领吸收一个参数即元素的 ID。以下面的元素为例:

<div id="myDiv">Some text</div>

能够运用下面的代码取得这个元素:

var div = document.getElementById("myDiv");
var div = document.getElementById("mydiv"); //无效的ID 然则能够在 IE7 及更早的版本中运用

假如文档中涌现多个 ID 雷同的元素,则取得第一次涌现的谁人。

IE7 及更早的版本在 name 特征与给定的 ID 婚配的表单元素(input textarea button select)也会被该要领接见。如:

<input type="text" name="myElement" value="hello">
<div id="myElement">Some text</div>

console.log(document.getElementById("myElement"));

所以最好不要把 id 与 name 设置成同一个称号。

getElementsByTagName()要领、HTMLCollection属性以及namedItem()要领

前者吸收一个参数即要去的的元素的标署名,后者则是该要领返回的对象,以下代码将取得一切 img 元素,并返回一个 HTMLCollection 对象:

<img src="" alt="">
<img src="" alt="">
<img src="" alt="">
<img src="" alt="">

console.log(document.getElementsByTagName("img").length); //4

这里返回的 HTMLCollection 对象能够经由过程方括号语法或 item() 要领来接见:

<body>
    <img src="" alt="">
    <img src="pics/topics.png" height="104" width="410" alt="">
    <img src="" alt="">
    <img src="" alt="">
    <script>
    var images = document.getElementsByTagName("img");
    console.log(images.length);
    console.log(images[1].src); //猎取src
    console.log(images.item(1).src); //猎取src
    </script>
</body>

别的,能够经由过程namedItem()要领来取得指定的 name 特征的项如:

<body>
    <img src="" alt="">
    <img src="pics/topics.png" height="104" width="410" alt="" name="secImg">
    <script>
    var images = document.getElementsByTagName("img");
    console.log(images.namedItem("secImg").src); //猎取了name特征为secImg的img标签的src
    </script>
</body>

固然也能够运用方括号语法:

<body>
    <img src="" alt="">
    <img src="pics/topics.png" height="104" width="410" alt="" name="secImg">
    <script>
    var images = document.getElementsByTagName("img");
    console.log(images.namedItem("secImg").src); //猎取了name特征为secImg的img标签的src
    console.log(images["secImg"].src); //与上面的雷同
    </script>
</body>

在背景,对数值索引就会挪用 item(),而对字符串索引就会挪用 namedItem()。

别的,能够向 getElementsByTagName() 中传入“*”。示意悉数标签;

getElementsByName()要领

该要领返回给定 name 特征的一切元素。最常常使用的状况是取得单选按钮。

<body>
    <fieldset>
        <legent>Which color do you perfer?</legent>
        <ul>
            <li>
                <input type="radio" name="color" value="red" id="colorRed">
                <label for="">Red</label>
            </li>
            <li>
                <input type="radio" name="color" value="green" id="colorGreen">
                <label for="">Green</label>
            </li>
            <li>
                <input type="radio" name="color" value="blue" id="colorBlue">
                <label for="">Blue</label>
            </li>
        </ul>
    </fieldset>
    <script>
        var radios = document.getElementsByName("color");
        console.log(radios[2].value); //blue
    </script>
</body>

在这里 namedItem() 要领只会取得第一项,因为每一项的 name 特征都是 color。

特别鸠合(.anchors/.forms/.images/.links)

  • document.anchors:文档中一切带 name 特征的 a 元素;

  • document.applets:文档中的一切 applet 元素。已不引荐运用 applet 元素了。

  • document.forms:文档中一切 form 元素

  • document.images:文档中一切 img 元素

  • document.links:文档中一切带 href 特征的 a 元素;

以下:

<form action=""></form>
<form action=""></form>
<img src="" alt="">
<a href="#">abc</a>
<a name="noName" href="#">abc</a>
<a name="noName" href="#">abc</a>

console.log(document.anchors.length); //2
console.log(document.forms.length); //2
console.log(document.links.length); //3

DOM 一致性检测

document.implementation属性与hasFeature()要领

因为 DOM 有多个级别,包含多个部份,因而检测浏览器完成了 DOM 的哪些部份黑白必要。该要领吸收两个参数:要检测的 DOM 功用的称号及版本号。假如浏览器支撑,则返回 true,如:

console.log(document.implementation.hasFeature("XML", "1.0")); //True

列表以下:

Core    完成 Node、Element、Document、Text 和其他一切DOM完成都要求完成的基础接口 一切恪守 DOM 范例的完成都必须支撑该模块。

HTML    完成 HTMLElement、HTMLDocument 和其他 HTML 专有接口。

XML 完成 Entity、EntityReference、ProcessingInstruction、Notation 和其他 XML 文档专用的节点范例。

StyleSheets 完成形貌一般样式表的简朴接口。

CSS 完成 CSS 样式表专有的接口。

CSS2    完成 CSS2Properties 接口。

Events  完成基础的事宜处置惩罚接口。

UIEvents    完成处置惩罚用户界面事宜的接口。

MouseEvents 完成处置惩罚鼠标事宜的接口。

HTMLEvents  完成处置惩罚 HTML 事宜的接口。

MutationEvents  完成处置惩罚文档变化事宜的接口。

Range   完成操纵文档局限的接口。

Traversal   完成举行高等文档遍历的接口。

Views   完成处置惩罚文档视图的接口。

文档写入

write()writeln()open()以及close()

个中,writeln() 会在字符串末了增加一个换行符(\n)如:

document.write("hello");
document.writeln("there"); //末了面有个换行符
document.write("anybodyHome?");
//hellothere anybodyHome?

另外,还能够运用 write() 和 writeln() 要领动态地包含外部资本。

须要注重的是,假如在文档加载终了后再实行 document.write 则会重写文档。

要领 open() 和 close() 离别用于翻开和封闭网页的输出流。

Element 范例

该范例用于表现 XML 或 HTML 元素,供应了对元素标署名、子节点及特征的接见。重要特征以下:

var x = document.getElementsByTagName("p")[0];
console.log(x.tagName); //P
console.log(x.nodeName); //P
console.log(x.nodeType); //1
console.log(x.nodeValue); //null
console.log(x.parentNode); //HTMLDivElement

其子节点多是 Element、Text、Comment、ProcessingInstruction、CDATASection 或 EntityReference。

因为 XML 和 HTML 的标署名大小写关联,在比较标署名的时刻最好先转换成小写,如:

var x = document.getElementsByTagName("p")[0];
if (x.tagName === "p") {
    console.log('testing1');
};
if (x.tagName.toLowerCase() === "p") {
    console.log('testing2');
};
//testing2

HTML元素

一切 HTML 元素都由 HTMLElement 范例示意,范例特征以下:

  • id:元素的唯一标识符;

  • title:附加申明信息;

  • lang:言语代码;

  • dir:言语方向;

  • className:元素的 class 特征对应,即 CSS 类。

如:

<div id="bd" class="myDiv" title="Body text" lang="en" dir="ltr"></div>

var div = document.getElementById("bd");
console.log(bd.dir); //ltr

别的另有其他浩瀚 HTML 元素以及与之关联的范例。这里不再累述。

取得特征

getAttribute()要领

该要领重如果取得特征的值;

须要注重的是,任何元素的一切特征,都能够经由过程 DOM 元素自身的属性来接见。然则自定义的特征不会以属性的情势增加到 DOM 对象中。如:

<div id="bd" my="hello" class="myDiv" title="Body text" lang="en" dir="ltr"></div>
<script>
var div = document.getElementById("bd");
console.log(div.my); //undefined(IE 除外)
</script>

因为种种缘由,应当只要在取得自定义特征值的状况下,才会运用该要领,如:

<div id="bd" my="hello" class="myDiv" title="Body text" lang="en" dir="ltr"></div>
<script>
var div = document.getElementById("bd");
console.log(div.my); //undefined(IE 除外)
console.log(div.getAttribute("my")); //应当用getAttribute要领接见自定义特征
</script>

别的须要注重的是,依据 HTML5 范例,自定义特征应当加上 data- 前缀以便考证,如:

<div id="bd" class="myDiv" title="Body text" lang="en" dir="ltr"></div>
<script>
var div = document.getElementById("bd");
div.setAttribute("data-my_attr", "value");
console.log(div.getAttribute("data-my_attr")); //value
console.log(div.attributes[5].name); //data-my_attr
</script>

设置特征

setAttribute()要领

该要领吸收两个参数:要设置的特征名和值。假如特征名存在,则实行替代操纵。如:

<div id="bd" class="myDiv" title="Body text" lang="en" dir="ltr"></div>
<script>
var div = document.getElementById("bd");
div.my = "hello";
console.log(div.getAttribute("my")); //null
console.log(div.my); //hello
</script>

综上所述,在取得特征值的状况下,最好用getAttribute()要领取得自定义特征,用 DOM 属性接见公认的特征;在设置特征值的状况下,最好用 DOM 属性来设置公认的特征,用setAttribute()要领设置自定义特征。如:

<div id="bd" class="myDiv" title="Body text" lang="en" dir="ltr"></div>
<script>
var div = document.getElementById("bd");

div.my = "value1";
console.log(div.my); //value1
console.log(div.getAttribute("my")); //null

div.setAttribute("my2", "value2");
console.log(div.my2); //undefined
console.log(div.getAttribute("my2")); //value2
</script>

总之,最好直接经由过程属性来读取和设置特征。

removeAttribute()要领

一个参数,IE6 及之前的版本不支撑该要领。如:

<div id="bd" class="myDiv" title="Body text" lang="en" dir="ltr"></div>
<script>
var div = document.getElementById("bd");

div.my = "hello";
console.log(div.my);

div.removeAttribute("my");
console.log(div.my);

div.setAttribute("my2", "value");
console.log(div.getAttribute("my2"));

div.removeAttribute("my2");
console.log(div.getAttribute("my2")); //null
</script>

attributes 属性

该属性包含一个 NamedNodeMap 对象,该对象有以下要领(不常常使用):

  • getNamedItem(Name):返回 nodeName 属性即是 Name 的节点;

  • removeNamedItem(Name):移除指定的节点;

  • setNamedItem(Node):增加指定的节点;

  • item(pos):返回位于数字 pos 位置的节点;

详细以下:

<div id="divId">
    <p id="pId">hhh</p>
</div>

var pId = document.getElementById("pId");
var namedItem = pId.attributes.getNamedItem("id").nodeValue;
console.log(namedItem); //pId
var attrList = pId.attributes.item(0).nodeValue; //pId
console.log(attrList);
pId.attributes.removeNamedItem("id");
console.log(pId.id); //

该属性常常涌来遍历元素的特征,如:

<p id="pId" name="para">hhh</p>

var pElem = document.getElementById("pId");

function outputAttributes(element) {
    var pairs = new Array();
    var attrName, attrValue, i, len;
    for (i = 0, len = element.attributes.length; i < len; i++) {
        attrName = element.attributes[i].nodeName;
        attrValue = element.attributes[i].nodeValue;
        pairs.push(attrName + "=\"" + attrValue + "\"");
    }
    return pairs.join(" ");
}
console.log(outputAttributes(pElem)); //id="pId" name="para"

然则须要强调的是:

  • 不通浏览器返回的递次不通;

  • IE7 及更早的版本会返回 HTML 元素中一切能够的特征,包含没有指定的特征

每一个特征节点都有一个名为 specified 的属性,这个属性的值假如为 true,则意味着要么是在 HTML 中制订了响应特征,要么是经由过程 setAttribute() 要领设置了该特征。

上面的代码兼容性斟酌,应当改成下面如许:

<p id="pId" name="para">hhh</p>

var pElem = document.getElementById("pId");

function outputAttributes(element) {
    var pairs = new Array();
    var attrName, attrValue, i, len;
    for (i = 0, len = element.attributes.length; i < len; i++) {
        attrName = element.attributes[i].nodeName;
        attrValue = element.attributes[i].nodeValue;
        if (element.attributes[i].specified) {
            pairs.push(attrName + "=\"" + attrValue + "\"");
        };
    }
    return pairs.join(" ");
}
console.log(outputAttributes(pElem)); //id="pId" name="para"

建立元素

createElement()要领

该要领吸收一个参数,即要建立元素的标署名。用该要领建立的新元素被给予了ownerDocument属性。随后经由过程appendChild()等要领增加到文档树中。如:

var newElementP = document.createElement("p");
var newElementPValue = document.createTextNode("data");
newElementP.title = "im title";
newElementP.appendChild(newElementPValue);
document.body.appendChild(newElementP);
console.log(newElementP.lastChild.nodeValue); //data
console.log(newElementP.title); //im title

在 IE 中能够用另一种体式格局运用 createElement(),即为这个要领传入完全的元素标签,也能够包含属性,但这类要领存在许多题目,不发起运用。(详细见《js高等程序设计》第十章节点条理 Element 范例)

元素的子节点

以下面代码为例:

<ul id="ulList">
    <li>1</li>
    <li>2</li>
    <li>3</li>
</ul>

var list = document.getElementById("ulList");
var childNodesList = list.childNodes;
console.log(childNodesList.length); //7

for (var i = childNodesList.length - 1; i >= 0; i--) {
    if (childNodesList[i].nodeType == 1) {
        console.log(childNodesList[i].nodeName); //LI*3
    };
};
for (var i = childNodesList.length - 1; i >= 0; i--) {
    if (childNodesList[i].nodeType == 3) {
        document.write(childNodesList[i].nodeValue); //LI*3的text节点值1、2、3
    };
};

犹如上面的代码一样,假如须要经由过程 childNodes 属性遍历子节点,呢么肯定要在操纵之前搜检 nodeType 属性。因为差别的浏览器会返回差别的节点个数:

<ul id="ulList"><li>1</li><li>2</li><li>3</li></ul>

这里才会返回 childNodesList.length 为3。

假如要返回上面代码中的一切 li 元素,能够运用以下代码:

var ulList = document.getElementById("ulList");
var liList = ulList.getElementsByTagName("li");
console.log(liList.length); //3

Text 范例

要注重的是,字符串会经由 HTML 或 XML 编码。如:

var pElem = document.getElementById("pId");
pElem.firstChild.nodeValue = "<p>hello there</p>";
console.log(pElem.innerHTML); //&lt;p&gt;hello there&lt;/p&gt

建立文本节点

createTextNode()要领

该要领建立文本节点,吸收一个参数即文本字符串。按理说一个元素只要一个文本节点,然则假如为其给予了多个节点,那末这些节点中的文本就会连起来,而且中心没有空格。如:

var newP = document.createElement("p");
var newPValue = document.createTextNode("data");
newP.appendChild(newPValue);
document.body.appendChild(newP);
var anotherPValue = document.createTextNode("anotherData");
newP.appendChild(anotherPValue); //dataanotherData

范例化文本节点

normalize()要领

该要领在一个包含两个或多个文本节点的父元素上挪用,将会把一切文本节点合成成一个节点。如:

var newP = document.createElement("p");
var newPValue = document.createTextNode("data");
newP.appendChild(newPValue);
document.body.appendChild(newP);
var anotherPValue = document.createTextNode("anotherData");
newP.appendChild(anotherPValue); //dataanotherData
console.log(newP.childNodes.length); //2
newP.normalize();
console.log(newP.childNodes.length); //1

支解文本节点

splitText()要领

这个要领将一个文本节点分红两个文本节点,本来的文本节点包含从最先到指定位置之前的内容;新的文本节点将包含剩下的文本。这个要领会返回一个新文本节点。如:

var newP = document.createElement("p");
var newPValue = document.createTextNode("data");
newP.appendChild(newPValue);
document.body.appendChild(newP);
var anotherPValue = document.createTextNode("anotherData");
newP.appendChild(anotherPValue); //dataanotherData

newP.normalize();
var anotherNewP = newP.firstChild.splitText(4);
console.log(newP.firstChild.nodeValue); //data
console.log(newP.lastChild.nodeValue); //anotherData

newP.normalize();
console.log(newP.firstChild.nodeValue); //dataanotherData

Comment 范例

createComment()要领

该要领能够建立诠释节点。不过鲜有人运用。具有除 splitText() 以外的一切字符串操纵要领。

CDATASection 范例

该范例只要在真正的 XML 文档中能够运用以下要领,浏览器会诠释他为 Comment 范例:

<div id="myDiv">
    <![CDATA[This is some content.]]>
</div>

console.log(document.getElementById("myDiv").firstChild); //Comment

createCDataSection()要领

该要领用来建立 CDATA 地区,只需为其传入节点的内容即可

DocumentType 范例

不常常使用。包含着与文档的 doctype 有关的一切信息。

该范例对象的三个属性:name、entities 和 notations。个中,name 示意文档范例的称号;entities 是由文档范例形貌的实体的 NamedNodeMap 对象;notations 是由文档范例形貌的标记的 NamedNodeMap 对象。一般来说只要 name 有点用。

console.log(document.doctype.name); //html

IE 不支撑。

DocumentFragment 范例

createDocumentFragment()要领

重要作用就是用来防止经由过程逐一增加元素所致使的浏览器重复衬着新信息的题目,运用一个文档片断来保留建立的元素,然后再一次性将它们增加到文档中。如:

<ul id="myList"></ul>

var fragment = document.createDocumentFragment();
var ul = document.getElementById("myList");
var li = null;

for (var i = 0; i < 3; i++) {
    li = document.createElement("li");
    li.appendChild(document.createTextNode("Item" + (i + 1)));
    fragment.appendChild(li);
};

ul.appendChild(fragment);

Attr 范例

该对象又3个属性:name、value 和 specified。但运用getAttribute()setAttribute()removeAttribute()要领更好用。

    原文作者:JS菌
    原文地址: https://segmentfault.com/a/1190000004130998
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞