简体   繁体   English

Google Chrome扩展删除元素

[英]Google Chrome Extension Remove Element

I am trying to remove an element from a div on a third party website. 我试图从第三方网站上的div中删除一个元素。

Such as

<div id="full_size_photo">
  <img src="img1">
  <img src="img2">
</div>


var imageDiv  = document.getElementById("full_size_photo");
imageDiv.removeChild(imageDiv.childNodes[i]);

imageDiv apparently has 5 children? imageDiv显然有5个孩子? :S When i is 1 img1 is removed properly. :S当我是1 img1被正确删除。 When i remove 3 and 4 img2 is removed... 当我删除3和4 img2被删除...

Would someone be able to explain why this is? 有人能够解释为什么会这样吗?

As far as I understand I thought the first img tag would be 0 and the second would be 1? 据我所知,我认为第一个img标签是0,第二个是1?

Whitespace stretches are textNode instances 空白延伸是textNode实例

Annotated example: 注释示例:

<div id="full_size_photo">[node 1 --
--]<img src="img1">[node 3 --
--]<img src="img2">[node 5 --
]</div>

Here's what you really want to do: 这是你真正想做的事情:

var div = document.getElementById("full_size_photo");
var images = div.getElementsByTagName("img");
div.removeChild(images[0]);

Hope this helps! 希望这可以帮助!

Most likely, the text nodes between the img nodes are what is tripping you up. 最有可能的是, img节点之间的文本节点正在绊倒你。 Try something like this: 尝试这样的事情:

var imgList = imageDiv.getElementsByTagName('img');
for (var i = imgList.length - 1; i >= 0; i--) {
  imageDiv.removeChild(imgList[i]);
}

Two things to note here: 这里有两点需要注意:

  • We are just searching through the children that are img nodes, not all children 我们只是搜索img节点的孩子,而不是所有孩子
  • We are looping through backwards, since we are removing nodes (otherwise, after removing node 1, we would increment the index to 2, but the node that was previously in position 2 would now be in position 1, so it would be skipped). 我们正在向后循环,因为我们正在删除节点(否则,在删除节点1之后,我们将索引增加到2,但先前在位置2的节点现在将位于位置1,因此将跳过它)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM