我正在尝试编写 javascript,通过使用 parentNode、firstChild、nextSibling、childNodes[] 等查找与给定元素相关的页面元素。 Firefox 通过在每个 html 元素之间插入文本节点来解决这个问题。我读过我可以通过删除元素之间的所有空格来解决这个问题,但我已经尝试过但它不起作用。有没有办法编写适用于所有现代浏览器的代码?
例如:
<div id="parent"><p id="child">Hello world</p></div>
在 IE 中,parent.firstChild 是子元素,但在 Firefix 中,它是一个幻影文本元素。
最佳答案
我有一个解决方法。您可以插入以下两种方法:
Element.prototype.fChild = function(){
var firstChild = this.firstChild;
while(firstChild != null && firstChild.nodeType === 3){
firstChild = firstChild.nextSibling;
}
return firstChild;
}
Element.prototype.nSibling = function(){
var nextSibling = this.nextSibling;
while(nextSibling != null && nextSibling.nodeType === 3){
nextSibling = nextSibling.nextSibling;
}
return nextSibling;
}
现在您可以使用:
document.getElementById("parent").fChild();
document.getElementById("parent").nSibling();
代替:
document.getElementById("parent").firstChild;
document.getElementById("parent").nextSibling;
关于javascript - 如何处理 Firefox 在标签之间插入文本元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/398816/