包装div的第一个div [英] Wrap first div of a div

查看:166
本文介绍了包装div的第一个div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想包装或替换名为entry-content的div中的第一个div和p:

I want to wrap or replace the first div and p which is in a div called entry-content :

var outer = document.getElementById(".entry-content div");
outer.innerHTML = "<div id='wrap'>"+outer.innerHTML+"</div>"

var outer = document.getElementById(".entry-content p");
outer.innerHTML = "<script type='text/javascript'>window.location = '"+outer.innerHTML+"'</script>"

输出(换行):

<div class="entry-content">
<div><div id="wrap">lala</div></div>
<p><script type="text/javascript">window.location = "http://"</script></p>
</div>

或最好的输出将是(换行和替换):

or the best output would be (wrap and replace):

<div class="entry-content">
<div id="wrap">lala</div>
<script type="text/javascript">window.location = "http://"</script>
</div>

感谢您的帮助!

推荐答案

看起来你想删除元素,但保留其内容。

It looks like you want to remove the element but keep its content. "Unwrap" if you want to call it that.

这可以通过一点DOM操作完成:

This can be done with a little DOM manipulation:

function unwrap(element) {
    // insert all the element's children *after* the element itself
    var parent = element.parentNode;
    var children = element.childNodes;
    var before = element.nextSibling;

    // reverse iteration always inserting the previous sibling before
    // the next one
    for (var i = children.length - 1; i > -1; i--) {
        before = parent.insertBefore(children[i], before);
    }

    // remove the element
    parent.removeChild(element);
}

然后你要做的只是传递一个对你想要的元素的引用删除该功能。

Then all you have to do is pass a reference to the element you want to remove to the function.

DEMO

如果您真的想要替换元素,那么您只需将所有子节点移动到新元素,并将旧元素替换为新元素一。我在这里调用函数重新包装(因为replace不表示内容被复制):

If you really want to replace the element though, then you just have to move all child nodes to the new element and replace the old element with the new one. I call the function "rewrap" here (because "replace" doesn't indicate that the content is copied):

function rewrap(element, new_element) {
    // append all the element's children to the new element
    while (element.firstChild) {
        new_element.appendChild(element.firstChild);
    }

    // replace old element with new
    element.parentNode.replaceChild(new_element, element);
}

演示

这篇关于包装div的第一个div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆