【问题标题】:Remove child element移除子元素
【发布时间】:2013-02-07 15:20:30
【问题描述】:

如何删除 foo label 以及 div 子元素和 br 的?

<label>qux</label>
<label>foo</label><div id="block">text</div><br /><br />
<label>bar</label>

我目前的临时方法:

$('label:contains("foo")').next().remove();
$('label:contains("foo")').remove();

我该如何改进?

【问题讨论】:

    标签: jquery


    【解决方案1】:

    很简单:

    $(元素).children().remove();

    这么简单……

    【讨论】:

      【解决方案2】:

      这里只是did on what html you posted

      试试这个:

       $('label:contains("foo")').remove(); // <-----------label contains foo removed
       $('#block').remove(); //<---------------------------div with id 'block' removed
       $('label:contains(qux)').nextAll('br').remove(); //<--finally all the br next to first label removed
      

      checkout on fiddle

      还有一个更好的.nextUntil():

      $('label:contains("qux")').nextUntil($('label:contains(bar)'),$('label, br')).remove();
      

      fiddle for .nextUntil()

      【讨论】:

        【解决方案3】:

        使用 .html() 方法并将其设置为 null。

        查看This 以供参考

        【讨论】:

          【解决方案4】:
          if($("label").text()=='foo'){
             $(this).next('div').remove();
             $(this).closest('br').remove(); 
          
             // I've used next and closest methods to remove..you can try with others..
          }
          

          【讨论】:

            【解决方案5】:

            试试这个:

            $('label').each(function(){
                var self = $(this);
                if(self.text() == 'foo'){
                      self.next('div').remove();
                      self.parent().find('br').remove(); //else use two times next() to remove two br tags.
                      self.remove();
                }
            });
            

            请提及.parent()中的父元素, 像这样:

            parent('div')  //if you have a parent container as div.
            

            【讨论】:

              【解决方案6】:

              我没有看到改进删除 foo &lt;label&gt; 的好方法。在语法上,您可以通过使用

              来改进 div 的删除
              $('label:contains("foo") + div').remove();
              

              CSS 相邻兄弟选择器。

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2019-05-27
                • 2013-10-31
                • 2022-08-23
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2013-04-22
                相关资源
                最近更新 更多