问题
Is there any way to remove element except inside element:
<div class=\"gallery\">
<a href=\"images/rep.png\" title=\"rep\">
<img src=\"http://example.com/uploads/rep.png\" class=\"thumbnail\" alt=\"rep\" title=\"rep\">
</a>
</div>
to
<div class=\"gallery\">
<img src=\"http://example.com/uploads/rep.png\" class=\"thumbnail\" alt=\"rep\" title=\"rep\">
</div>
I wrote this code but not work:
$(\".gallery\").contents().filter(\".thumbnail\").remove();
回答1:
jQuery has an unwrap()
method which removes the parent node and leaves the matched element in place:
$(".gallery").contents().filter(".thumbnail").unwrap();
// or (faster)
$(".gallery .thumbnail").unwrap();
- http://api.jquery.com/unwrap/
回答2:
$(".thumbnail").unwrap()
http://api.jquery.com/unwrap/
回答3:
Might be a simpler method, but:
$('.gallery').each( function() {
var img = $(this).find('img');
$(this).children("a").remove();
$(this).append(img);
});
回答4:
try
innerhtml = $("div.gallery .thumbnail").get();
$("div.gallery").html(innerhtml);
来源:https://stackoverflow.com/questions/7951699/jquery-remove-element-except-inside-element