jQuery : remove element except inside element

回眸只為那壹抹淺笑 提交于 2019-11-26 04:56:53

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!