codecamp

XML DOM firstChild 属性

XML DOM firstChild 属性


Node 对象参考手册 Node 对象

定义和用法

firstChild 属性返回指定节点的第一个子节点。

语法

nodeObject.firstChild


提示和注释

注释:Firefox 以及大多数其他的浏览器,会把节点间生成的空的空格或者换行当作文本节点,而 Internet Explorer 会忽略节点间生成的空白文本节点。因此,在下面的实例中,我们会使用一个函数来检查第一个子节点的节点类型。

元素节点的节点类型是 1,因此如果第一个子节点不是一个元素节点,它就会移至下一个节点,然后继续检查此节点是否为元素节点。整个过程会一直持续到第一个元素子节点被找到为止。通过这个方法,我们就可以在所有的浏览器中得到正确的结果。

提示:如需了解更多有关浏览器差异的知识,请在我们的 XML DOM 教程中访问我们的 DOM 浏览器 章节。


实例

下面的代码片段使用 loadXMLDoc() 把 "books.xml" 载入 xmlDoc 中,并显示第一个子节点的节点名称和节点类型:

实例

//check if the first node is an element node
function get_firstchild(n)
{
x=n.firstChild;
while (x.nodeType!=1)
{
x=x.nextSibling;
}
return x;
}

xmlDoc=loadXMLDoc("books.xml");

x=get_firstchild(xmlDoc);
document.write("Nodename: " + x.nodeName);
document.write(" (nodetype: " + x.nodeType);

输出:

Nodename: bookstore (nodetype: 1)

尝试一下 »

尝试一下 Demos

取得文档的最后一个子节点


Node 对象参考手册 Node 对象
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }