Jump to content

Check if an element already exists


ShadowMage
 Share

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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...