insertAdjacentHTML的用法,我用的很少,不知道大家频繁不……

    <li>内容1</li>
    <li>内容2</li>
    <li>内容3</li>
    <li>内容4</li>


    一般我们用下面的方法居多(appendChild) :
    var _li = document.createElement('li');
    document.querySelector("ul").appendChild(_li);

    insertBefore我一般也很少使:
    var _dom = document.querySelector("ul");
    var _li = document.createElement('li');
    if(_dom.children){
        _dom.insertBefore(_li,_dom.children[1])
    }else{
        _dom.appendChild(_li);
    }
    document.querySelector("ul").insertAdjacentHTML('beforeend','<li>89</li>')

    其实下面这种方法更好使,并且insertAdjacentHTML是插入文本会解析html标签:
    document.querySelector("ul").insertAdjacentHTML("afterbegin","<li>5555</li>");
    beforebegin  //在 element 元素的前面。
    afterbegin   //在 element 元素的第一个子元素前面。
    beforeend    //在 element 元素的最后一个子元素后面。
    afterend     //在 element 元素的后面。


    火狐不支持这个insertAdjacentText,另外insertAdjacentElement在火狐中也不支持,同样使用下面的兼容代码:
    (function(){  
        if(!!window.sidebar && HTMLElement.prototype.insertAdjacentText == undefined) {  
            HTMLElement.prototype.insertAdjacentElement = function(where, node) {  
                switch (where) {  
                    case "beforebegin":  
                        this.parentNode.insertBefore(node, this);break;  
                    case "afterbegin":  
                        this.insertBefore(node, this.firstChild);break;  
                    case "beforeend":  
                        this.appendChild(node);break;  
                    case "afterend":  
                        if (this.nextSibling)  
                            this.parentNode.insertBefore(node, this.nextSibling);  
                        else  
                            this.parentNode.appendChild(node);  
                        break;  
                };  
            };  
            HTMLElement.prototype.insertAdjacentText = function(where, txt) {  
                var parsedText = document.createTextNode(txt);  
                this.insertAdjacentElement(where, parsedText);  
            };  
        };  
    })(); 复制代码
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值