【问题标题】:Replace an HTML element with some HTML contained in a string用字符串中包含的一些 HTML 替换 HTML 元素
【发布时间】:2011-10-29 23:16:32
【问题描述】:

假设我有这部分 HTML 文档:

<div>hello world <span id="test"></span></div>

在纯 JavaScript 中,我需要将 span 替换为包含在字符串中的一些 HTML 内容,例如 '&lt;span&gt;other&lt;/span&gt; yo &lt;a href="www.google.ca"&gt;google&lt;/a&gt;'

所以最终结果是这样的:

<div>hello world <span>other</span> yo <a href="www.google.ca">google</a></div>

我面临的问题是 HTML 字符串可以在其“根”处包含任意数量的标签。所以这不是标签的一对一替换。

我需要直接用 JavaScript(没有 jQuery)来做。

如果有人可以帮忙!

谢谢

【问题讨论】:

    标签: javascript html xml-parsing


    【解决方案1】:

    您不能只设置&lt;span id="test"&gt; 的innerHTML 的原因是什么?拥有额外的跨度并没有什么坏处......

    如果你真的需要移除外部跨度,你可以在它之前插入所有的childNodes。

    var html = '<span>other</span> yo <a href="www.google.ca">google</a>';
    
    var removeMe = document.getElementById('test');
    removeMe.innerHTML = html;
    
    var child;
    while(child = removeMe.childNodes[0]) {
        removeMe.parentNode.insertBefore(child, removeMe);
    }
    
    removeMe.parentNode.removeChild(removeMe);
    

    http://jsfiddle.net/4tLVC/1/

    【讨论】:

    • 我实际上使用了你的技术,但我没有在“removeMe”中工作,而是创建了一个未附加的“div”元素并将内容插入其中,它可能会快一点,因为 dom 对象不是附在主文件中。但非常感谢它解决了我的问题:)
    • 我终于用上了这段代码:看来我用你的失去了'yo'文本节点...jsfiddle.net/4zMha但是再次感谢!
    • 啊,错误是 i 增加但节点从列表中删除,所以它被跳过,修复代码和 jsfiddle
    【解决方案2】:

    你不能用吗

     var span = document.getElement...('test')
     div.getElementById('yourDiv').removeChild(span)
    

    其实你也可以

    span.parentNode.removeChild(span)
    

    这应该可以。 之后

     div.innerHTML += 'your cool <span>content></span>'
    

    【讨论】:

    • 显然有人不喜欢我 ;-)
    猜你喜欢
    • 1970-01-01
    • 2015-09-16
    • 1970-01-01
    • 2022-11-14
    • 1970-01-01
    • 2011-01-15
    • 2021-11-26
    • 2014-09-12
    • 1970-01-01
    相关资源
    最近更新 更多