javascript - 如何处理 Firefox 在标签之间插入文本元素

标签 javascript html firefox

我正在尝试编写 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/

相关文章:

javascript - 仅验证表单的可见部分

javascript - Jquery .position 为 null 转换为 0

ios - html5视频标签: mp4 video not supported on iOS

javascript - 在 Internet Explorer 中调试 Javascript : display not updating

javascript - 在没有内联脚本的情况下处理图像加载错误

html - 如何从 Firefox 中的选择元素中删除箭头

google-chrome - PDF文档文本在IE/Firefox/Chrome浏览器中的显示方式有所不同

css - 由于 CSS 问题,页面无法在 IE 和 Firefox 中正确显示

javascript - 语法错误 : Cannot use import statement outside a module

javascript - ng-change 如果所选值大于 6,则更改 td 背景颜色