最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to remove all siblings in JavaScript? - Stack Overflow

programmeradmin7浏览0评论

I have four images and I want to remove the other 3 when anyone is clicked.

I could do it one by one with:

function removeimages() {
var elem = document.getElementById('image1');
elem.parentNode.removeChild(elem);
}

but that is not practical.

What is the best way to remove all the siblings (images) except the one clicked?

I have four images and I want to remove the other 3 when anyone is clicked.

I could do it one by one with:

function removeimages() {
var elem = document.getElementById('image1');
elem.parentNode.removeChild(elem);
}

but that is not practical.

What is the best way to remove all the siblings (images) except the one clicked?

Share Improve this question edited Mar 24, 2014 at 16:48 Ivanyosan asked Mar 24, 2014 at 16:30 IvanyosanIvanyosan 1511 silver badge3 bronze badges 3
  • 3 Have you tried anything? – j08691 Commented Mar 24, 2014 at 16:31
  • Show us the code that you have been trying before you posted your question. – lshettyl Commented Mar 24, 2014 at 16:32
  • allthethings.onclick = function(){ for(var i = 0; i < document.images.length; i++){ if(document.images[i] == this)continue;document.images[i].parentNode.removeChild(document.images[i]);} }; – Travis J Commented Mar 24, 2014 at 16:34
Add a ment  | 

1 Answer 1

Reset to default 7

Why don't you try to use jquery to manipulate the DOM? It will be much easier and be supported by most browsers. The code is as follows:

$("#imgContainer img").click(function () {
    $(this).siblings().remove();
});

Please have a look at this working version: JS Fiddle

发布评论

评论列表(0)

  1. 暂无评论