简体   繁体   English

如何删除特定标签innerHTML之前的所有内容

[英]How to remove everything before a specific tag innerHTML

I have a function which generates a bunch of span tags one after another, some are slightly unique with a unique class given to it...I would like to find a function that deletes/clears everything before a certain tag....so this is what the html would look like: 我有一个函数,一个接一个地生成一堆span标签,有些稍微有些独特,并赋予了一个唯一的类...我想找到一个删除/清除某个标签之前所有内容的函数....所以这就是html的样子:

    <div id="wordsBox">
        <span>bla</span>
        <span>bla</span>
        <span class="lastword">bla</span>
        <br />
        <span>bla</span>
        <span>bla</span>
        <span>bla</span>
        <span>bla</span>
    </div>

Basically when it hits the class lastWord when I am cycling through the spans, want to delete the it and the spans before it. 基本上,当我在跨度中循环时,当它碰到了lastWord类时,要删除它和之前的跨度。

You want to use prevAll() 您想使用prevAll()

 $(".lastword") //select the div with the class .prevAll() //select all of the previous siblings .addBack() //adds the "lastword" element into the collection .remove(); //remove the elements 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="wordsBox"> <span>bla</span> <span>bla</span> <span class="lastword">bla</span> <br /> <span>bla</span> <span>bla</span> <span>bla</span> <span>bla</span> </div> 

This does what you want: 这就是您想要的:

$( "#wordsBox .lastword" ).prevAll().remove();
$( "#wordsBox .lastword" ).remove();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM