用它替换元素的内容IE8

时间:2014-03-14 21:45:10

标签: javascript jquery internet-explorer-8

我正在尝试更换一些"嵌套"一些HTML的类与javascript / jquery。我需要用class =" foo"来摆脱跨度。并且只留下"东西"。

<ul>
<li>
<span class="foo">stuff
<ul>
<li><span class="foo">stuff</span>
</li>
</ul>
</span>
</li>
</ul>

这适用于除IE8之外的所有内容(我必须支持):

$(".foo").each(function () {
$(this).replaceWith(this.innerHTML);
});

在有人指出还有其他类似的问题之前,请注意我已尝试过这些问题中列出的几种方法,我认为我的用例因为&#34;嵌套&#34;而有所不同。我已尝试过本网站和其他主题的解决方案。其中一些完全崩溃IE8,其他人只是不工作。

我知道在replaceWith之前尝试使用.empty(),但这并没有帮助......我的问题不是性能(还有)它甚至可以使用它。< / p>

我也试过这个:

$(".foo").each(function () {
    var HTMLshunt = this.innerHTML;
    $(this).after(HTMLshunt).remove();
});

为什么&#34; HTMLshunt&#34; VAR?我的工作前提是它可能不在IE8中工作,因为&#34;之后&#34;在&#34;之后没有真正去过&#34; .foo,但在它里面...因为在IE8中有一些事情发生在这个:它消除了每个.foo,但没有留下foo的内容。

这个&#34;嵌套&#34;没有帮助。我认为如果它不是嵌套的话,沿途拼凑的其他东西也会起作用,但它并不重要,因为有这种嵌套。如果有人可以提供帮助,请回复。

2 个答案:

答案 0 :(得分:0)

你可以试试这个,应该是IE8友好的(虽然我相信jQuery 1.11.0也应该支持IE8)。如果回流是任何担心,那么你可以cloneNode首先以牺牲一些内存为代价。

HTML

<ul>
    <li>
        <span class="foo">stuff
            <ul>
                <li>
                    <span class="foo">stuff</span>
                </li>
            </ul>
        </span>
    </li>
</ul>

的Javascript

var fooClasses = document.querySelectorAll('.foo'),
    fooIndex,
    foo,
    fragment;

for (fooIndex = fooClasses.length - 1; fooIndex >= 0; fooIndex -= 1) {
    fragment = document.createDocumentFragment();
    foo = fooClasses[fooIndex];
    while (foo.firstChild) {
        fragment.appendChild(foo.firstChild);
    }

    foo.parentNode.replaceChild(fragment, foo);
}

jsFiddle

使用克隆节点

var fooClasses = document.querySelectorAll('.foo'),
    fooIndex,
    foo,
    fragment,
    clone;

for (fooIndex = fooClasses.length - 1; fooIndex >= 0; fooIndex -= 1) {
    fragment = document.createDocumentFragment();
    foo = fooClasses[fooIndex];
    clone = foo.cloneNode(true);
    while (clone.firstChild) {
        fragment.appendChild(clone.firstChild);
    }

    foo.parentNode.replaceChild(fragment, foo);
}

jsFiddle

答案 1 :(得分:0)

好像你正在使用jQuery。在这种情况下,您应该只使用unwrap()方法:

  

描述:从DOM中删除匹配元素集的父节点,将匹配的元素留在原位。

举个例子:

$(".foo").each(function () {
  $(this).children().unwrap();
});

jsFiddle demonstration

这个小提琴使用jQuery 1.9.1,所以它应该在IE8中运行。

修改

好的,问题是当节点只包含文本内容时jQuery.unwrap不起作用。

为了处理文本内容,您必须使用稍微不同的方法:

$(".foo").each(function() {
    $(this).replaceWith(this.childNodes);
});

See this fiddle

完全披露:我使用了this answer来进行此项技术。