views:

30

answers:

2

I am trying to remove an element from a div on a third party website.

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? :S When i is 1 img1 is removed properly. When i remove 3 and 4 img2 is removed...

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?

+1  A: 

Whitespace stretches are textNode instances

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!

jimbojw
You could also use the nodeType property to detect if it is an element or a text node. See http://www.w3schools.com/dom/prop_node_firstchild.asp for more info.
Greg Bray
Your code makes a lot more sense and you have also explained my problems quite clearly.Thank you very much.
John O'Fish
A: 

Most likely, the text nodes between the img nodes are what is tripping you up. 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
  • 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).
pkaeding