jQuery从变量中删除HTML元素

4

我有一个存储在变量中的HTML代码

var  itinerary =  $('.events_today').html() ;

我有很多HTML代码,其中一个按钮我想要移除。它的ID是“myButton”。我该如何从保存在我的变量中的HTML代码中将其移除?


这个很难。我想看看最好的方法是什么。有没有可能在添加后不能删除它? - Leeish
@Roscoeh,你尝试过一些提出的解决方案吗? - Fabrizio Calderan
5个回答

10

我建议采用这种方法

var itinerary = $('.events_today')
                .clone(true)       /* get a clone of the element and from it */
                .find('#myButton') /* retrieve the button, then */
                .remove()          /* remove it, */
                .end()             /* return to the previous selection and */
                .html() ;          /* get the html */

1

试试这个:

itinerary.filter(function() { return $(this).not("#myButton"); });

这对我有帮助,可以从Ajax响应中删除元素,例如:$(response).not('#element_id'); - TomoMiha

0

只需通过其id定位元素并删除:

$('#myButton').remove()

然后获取您的行程:

var itinerary =  $('.events_today').html() ;

// 上面的代码将会从DOM中移除该按钮。如果你只是想要获取html而不移除DOM中的按钮,可以这样做:

var itinerary = $('.events_today').clone(true).find('#myButton').remove().end().html();

1
我认为他不想从DOM中删除它,只是想删除变量。 - Zachary Kniebel

0
在集合中查找元素并将其删除。

$('.events_today').find('#myButton').remove();

编辑:在意识到我可能误解了原帖后,这个方法可能可行(虽然不是非常美观)。

var html = $('.events_today').html();
// Parse the html, but don't add it to the DOM
var jqHtml = $(html);
// Find and remove the element with the specified id.
jqHtml.find('#myButton').remove();
// Get the new html without the myButton element.
var result = jqHtml.html();

更新:根据@Fabrizio Calderan的答案,您可以使用jQuery方法更好地完成上述操作。


请看我的评论,针对qci的回答。 - Zachary Kniebel

0

试试这个:

var html = $('#myHtml').clone(true).find('#elementThatYouWantToRemove').remove().end().html();

你为什么要克隆父元素? - Uyghur Lives Matter

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接