Jump to content

Check if an element already exists


ShadowMage

Recommended Posts

Another question here. I have an element that I cloned from another element. This element is added and removed from a container, based on a user action. Problem is, if I try to remove the element before it's been added, I get an error. Something about "couldn't find node" which makes sense. But how do I detect whether the node exists or not?Here's some code to hopefully help explain a little bit:Create a clone:var newElem = anotherElem.cloneNode(true);User adds the cloned node to the container:container.appendChild(newElem);User removes the cloned node from the container:container.removeChild(newElem);Now if the user tries to remove the node before it's been appended (it's been created via cloneNode but it hasn't been added to the DOM yet) the script blows up. So what I need is something like:if (container.contains(newElem)) {container.removeChild(newElem);}I've tried checking the parentNode of newElem which works in FireFox (it returns null like I would expect) but IE returns a "document fragment" or some such. :)Anybody know a good way to do this?TIA.

Link to comment
Share on other sites

You can still check if the parent node is the container:

// Don't throw an error in the case that newElem doesn't have a parentNode property.if(newElem.parentNode && newElem.parentNode == container) {  container.removeChild(newElem);}

Link to comment
Share on other sites

You can still check if the parent node is the container:
// Don't throw an error in the case that newElem doesn't have a parentNode property.if(newElem.parentNode && newElem.parentNode == container) {  container.removeChild(newElem);}

Thx! That did the trick. I never thought to compare the two....
Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...