删除给定子元素之后的所有内容(元素和文本)

时间:2019-02-06 21:48:56

标签: javascript

我现在正在使用Gmail扩展程序,并且鉴于我拥有父元素,并且它看起来类似于下图,因此我需要删除<br clear="all" />之后的所有内容,因为之后可能有无根据用户的Gmail签名设置存在。有想法吗?

<div
    id=":93"
    class="Am Al editable LW-avf"
    hidefocus="true"
    aria-label="Message Body"
    g_editable="true"
    role="textbox"
    aria-multiline="true"
    contenteditable="true"
    tabindex="1"
    style="direction: ltr; min-height: 416px;">
    Test
    <br clear="all" />
    <div>
        <br />
    </div>
    -- <br />
    <div dir="ltr" class="m_-1358982132021700848m_4914548661371847332gmail_signature" data-smartmail="gmail_signature">
        <div dir="ltr">
            <b>Suzy Smith</b>
            <div>
                <i><a href="mailto:suzysmith@mail.com" target="_blank">suzysmith@mail.com</a></i>
            </div>
        </div>
    </div>
</div>

1 个答案:

答案 0 :(得分:3)

只需遍历nextSibling并将其删除。

var elem = document.querySelector('[clear="all"]')
while(elem.nextSibling) {
  elem.nextSibling.remove()
}
elem.remove()
<div
    id=":93"
    class="Am Al editable LW-avf"
    hidefocus="true"
    aria-label="Message Body"
    g_editable="true"
    role="textbox"
    aria-multiline="true"
    contenteditable="true"
    tabindex="1"
    style="direction: ltr; min-height: 416px;">
    Test
    <br clear="all" />
    <div>
        <br />
    </div>
    -- <br />
    <div dir="ltr" class="m_-1358982132021700848m_4914548661371847332gmail_signature" data-smartmail="gmail_signature">
        <div dir="ltr">
            <b>Suzy Smith</b>
            <div>
                <i><a href="mailto:suzysmith@mail.com" target="_blank">suzysmith@mail.com</a></i>
            </div>
        </div>
    </div>
</div>