Ответ 1
var save = $('#test .notsure').detach();
$('#test').empty().append(save);
Как удалить все внутри div
кроме div/span
с помощью class='notsure'
? Я могу удалить всех детей с помощью empty
, но не уверен, как сохранить конкретный div
.
<div id="test">
here is a test
<p>a paragraph</p>
<div class="notsure"></div>
</div>
var save = $('#test .notsure').detach();
$('#test').empty().append(save);
Update:
Если вы также хотите удалить текст here is a test
:
var notsure = $('.notesure');
$('#test').html('').append(notsure);
$('#test').children().not('.notsure').remove();
Попробуйте это
$("#test").children().filter(":not(.notesure)").remove();
Вы можете отфильтровать его содержимое:
var b = $('#test').contents();
b.filter(function() { //
return this.nodeType == 3; //Node.TEXT_NODE
}).remove()
.end().filter(':not(.notesure)').remove(); //Find the elements that don' t have the .notesure class.;
$('.notesure').click(function(){
$(this).html('clicked !!');
}
Пример. http://jsbin.com/urudew/2/edit
.notsure
$('.notsure').clone(true).appendTo($('#test').empty());
Удалите true
из clone(true)
, чтобы избавиться от .notsure
связанных событий, таких как клик и т.д.
Если вы не заинтересованы в событиях, привязанных к этим элементам, вы можете просто сделать:
$('.notsure').appendTo($('#test').empty());
вы можете проверить это Ниже приведен рабочий пример
$(function () {
$('#delete-button').click(function () {
deleteElementsBelow('#parent-container');
});
function deleteElementsBelow(parentContainerSelector) {
var save = $('#parent-container #delete-button').detach();
$(parentContainerSelector).empty().append(save);
}
});
здесь можно сделать трюк...
$("#test").html('<div class="notesure">'+$('div.notesure').html()+'</div>')