相反在jquery中追加

时间:2011-02-08 14:49:56

标签: javascript jquery

我使用.append添加到div

$(this).append('<ul><li>test</li></ul>');

我如何搜索<ul>并将其删除(如果$(this)的子项中存在?

6 个答案:

答案 0 :(得分:83)

您可以使用remove()。有关jQuery remove()的更多信息。

$(this).children("ul").remove();

请注意,这会删除所有 ul个子元素。

答案 1 :(得分:18)

使用remove()方法:

$(this).children("ul").remove();

答案 2 :(得分:18)

.append()相反的是.prepend()

来自jQuery documentation for prepend…

  

.prepend()方法将指定的内容作为jQuery集合中每个元素的第一个子元素插入(要将其作为最后一个子元素插入,请使用.append())。

我意识到这不符合OP的具体案例。但它确实回答了问题标题。 :)这是谷歌首次对“jquery对立追加”进行了点击。

答案 3 :(得分:13)

您还应该考虑的是保留对已创建元素的引用,然后您可以轻松地将其删除:

   var newUL = $('<ul><li>test</li></ul>');
   $(this).append(newUL);

   // Later ...

   newUL.remove();

答案 4 :(得分:8)

刚遇到同样的问题,我遇到过这个问题 - 实际上这对我来说很有用:

// $("#the_div").contents().remove();
// or short: 
$("#the_div").empty();
$("#the_div").append("HTML goes in here...");

答案 5 :(得分:5)

对面是children(),但位置相反是prepend()。 Here一个非常好的教程。