views:

73

answers:

4

I am getting a javascript error on a page with this code.The error is "parentNode is null or not and object"

The error is in this line: theParent.parentNode.removeChild(theParent);

Is there some other code I can use to replace this or jquery that will work instead?

var path = location.pathname;

if( path == "/SearchResults.asp" 
 || path == "/ProductDetails.asp" 
 || path.indexOf("-s/") != -1 
 || path.indexOf("_s/") != -1 
 || path.indexOf("_p/") != -1 
 || path.indexOf("-p/") != -1 ) {
    var links = document.getElementById("content_area")
                        .getElementsByTagName("a");
    var homeLink;
    for (var i = 0; i < links.length; i++) {
        if (links[i].innerHTML.match("Home")) {
                homeLink = links[i];
                break;
        }
    }
    var theParent = homeLink.parentNode;
    theParent.parentNode.removeChild(theParent);
}
A: 

It seems your loop may not be finding a link with the text Home. Have you tried checking if homeLink is null?

Darko Z
A: 

Looks like either homeLink is null or the parentNode is null. Can you run it in firefox + firebug and set breakpoints?

BrennaSoft
+1  A: 

Try

if (theParent) { theParent.parentNode.removeChild(theParent); }

Since, it looks like you may not be finding the innerHTML, "Home" or not creating theParent for some other reason.

The HTML would help, just to make sure Home exists and that it has a grand parent.

Peter Ajtai
+1  A: 

It seems strange that you'd get "parentNode is null or not and object" with:

var theParent = homeLink.parentNode;

If anything, it would simply set theParent to null and continue on. Or, homeLink would need to be the cause of the error, which is not what IE is complaining about.

However, the next line...

theParent.parentNode.removeChild(theParent);

...I could see throwing the error mentioned if parentNode was null, since null cannot have methods, such as removeChild.

You can try revising the line to something like the following to get an idea of success rate:

if (theParent.parentNode == null) // == for null or undefined by coercion
    theParent.parentNode.removeChild(theParent);
else
    throw new Error('Node could not be removed as parentNode is unknown.');

Or, leave out the else and throw to let it fail silently.

Jonathan Lonowski
my appologies, the error is in theParent.parentNode.removeChild(theParent);