jquery展开多个递归节点

时间:2016-04-22 22:19:22

标签: javascript jquery

我正在尝试删除所有具有类'toBeRemoved'的div,我不太清楚如何去做。我考虑打开包装,但未能接近我正在寻找的任何地方。

是否可以轻松地从中获取:

gradle assembleDebug

<div class="toBeRemoved">
    <div class="toBeRemoved">
        <table>
            <tbody>
                <tr>
                    <td>
                        <div class="toBeRemoved">
                            <div class="toBeRemoved">
                                <div style="text-align: left;">
                                    <div class="toBeRemoved">
                                        <div class="toBeRemoved">
                                            First node
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
    <div class="toBeRemoved">
        <table>
            <tbody>
                <tr>
                    <td>
                        <div class="toBeRemoved">
                            <div class="toBeRemoved">
                                <div style="text-align: left;">
                                    <div class="toBeRemoved">
                                        <div class="toBeRemoved">
                                            Second node.
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
</div>

2 个答案:

答案 0 :(得分:2)

将每个.toBeRemoved元素替换为其直接子元素:

$('.toBeRemoved').each(function() {
  $(this).replaceWith($(this).children());
});

Fiddle

答案 1 :(得分:1)

.remove() 无效。因为它会移除孩子。

var cnt = $(".toBeRemoved").contents();
$(".toBeRemoved").replaceWith(cnt);

从这里开始。 How to remove only the parent element and not its child elements in JavaScript? 重复帖子。

编辑应该立即工作

$(".toBeRemoved").each( function () {
    var cnt = $(".toBeRemoved").contents();
    $(".toBeRemoved").replaceWith(cnt);
});