我有一个存储在变量中的HTML代码
var itinerary = $('.events_today').html() ;
我有很多HTML代码,其中一个按钮我想要移除。它的ID是“myButton”。我该如何从保存在我的变量中的HTML代码中将其移除?
我建议采用这种方法
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 */
试试这个:
itinerary.filter(function() { return $(this).not("#myButton"); });
只需通过其id定位元素并删除:
$('#myButton').remove()
然后获取您的行程:
var itinerary = $('.events_today').html() ;
// 上面的代码将会从DOM中移除该按钮。如果你只是想要获取html而不移除DOM中的按钮,可以这样做:
var itinerary = $('.events_today').clone(true).find('#myButton').remove().end().html();
$('.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方法更好地完成上述操作。
试试这个:
var html = $('#myHtml').clone(true).find('#elementThatYouWantToRemove').remove().end().html();