javascript error in ie7 - javascript

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);
}

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.

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.

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

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

Related

If statement run if empty string

If I do this in the console:
document.querySelectorAll('.error')
An object of length 3 is returned.
If any of the property values are empty, then I do not want my if statement to run:
After getting frustrated with this (I was using != '') the internet told me to use !== ""
Here is the output for property in the object:
document.querySelectorAll('.error')[0]
""
document.querySelectorAll('.error')[1]
"some string"
document.querySelectorAll('.error')[2]
""
My newness to JS is probably apparent by my question so far. Is the "best" way to check for empty string to use what I have done !==?
<script>
var errorElems = document.querySelectorAll('.error');
for(i=0; i<errorElems.length; i++) {
if(errorElems[i].textContent !== ""){
dataLayer.push({
"event": "errors",
"eventCategory": "error messages",
"eventAction": errorElems[i].id,
"eventLabel": errorElems[i].textContent
})
};
};
This appears to be working. But I'm one person checking in one browser (Chrome) on a desktop machine, if that matters.
What would be the most full proof (yet reasonably straightforwards) means to doing this? Is !== best test?
If its an empty string, !== "" is the way to go. If it can be undefined too (as it very much can happen when selecting DOM elements), then you should make a check like this:
if (typeof string !== 'undefined' && string !== "")
empty values are parsed as false, if you just try
if (!errorElems[i].textContent) {
... // error handling code here
}
The Node.textContent property, as per its specification can return a null value, so it would be better to test it with something like this:
var errorElems = document.querySelectorAll('.error'),
errorElem;
for (i=0; i < errorElems.length; i++) {
errorElemText = errorElems[i].textContent;
if (typeof errorElemText === "string" && errorElemText !== "") {
dataLayer.push({
"event": "errors",
"eventCategory": "error messages",
"eventAction": errorElems[i].id,
"eventLabel": errorElemText
});
}
}

Javascript stops executing rest of the OR

This is just a simple JavaScript form-validation that i put together, all the document.form.*.value exist on my page, except for the document.form.dasdasdas.value ==''
In the following code, with the point of it being to give an error if any of the forms are empty, in this case however, because i assume dasdasdas is not a form on my page, it doesn't, and my question is why.
Even though it doesn't exist, doesn't that make it empty?
My question is: Why does, after i filled everything in ( customername to customerpostcode ) and leave customerbank and customercity empty, it still says everything is oke ?
After deleting that line everything works just fine, but i'm curious to why it behaves like this!
An answer to this, not so good explanation would be, awesome!
Here is my code.
function FileChecked()
{
if( document.form.customername.value =='' ||
document.form.customerpassword.value =='' ||
document.form.customerphone.value =='' ||
document.form.customeremail.value =='' ||
document.form.customeradres.value =='' ||
document.form.customerpostcode.value =='' ||
document.form.dasdasdas.value =='' ||
document.form.customerbank.value =='' ||
document.form.customercity.value =='')
{
alert('Not all forms are filled.');
return false;
}
// Check if file is selected and extension is .csv
if(document.form.csvfile.value =='')
{
alert('No file given');
return false;
}
else
{
ext = document.form.csvfile.value.toLowerCase();
if(ext.substr(ext.length-4) == '.csv')
{
return true;
}
else
{
alert ('Filetype is not .csv');
return false;
}
}
}
If document.form.dasdasdas doesn't exist, then it's undefined. You can't get the property value of undefined - hence the error.
You'd want to do something like
... || (document.form.dasdasdas === undefined || document.form.dasdasdas.value == '') || ...
but like i said, if document.form.dasdasdas doesn't exist on the DOM then it'll be pretty hard for someone to fill it in.
When you try to get the value property of an element then it should be exist on the page or in DOM itself.
document.form.dasdasdas
I believe here you are trying to get a value of an non existing element so when you are trying to get it's value property it gives you undefined.
To avoid this first you need to check this for undefined and then get it's value and do your comparision
(document.form.dasdasdas != undefined || document.form.dasdasdas.value == '')

JavaScript...Cannot call method match of undefined

I'm getting this error: Uncaught TypeError: Cannot call method 'match' of undefined in my JavaScript. I'm trying to write this without jQuery since it'll be the only js on the site.
My code is supposed to add a class, "active", to the <a href="...> in the navigation that links to the current page.
I'm guessing it might be the contentLoaded function?....source
Here's my code...(error occurs on line 9)...fiddle
(function(window, document, undefined) { contentLoaded(window, function() {
var page = document.location.pathname.match(/[A-z]+$/)[0],
nav_anchors = document.getElementsByTagName('header')[0]
.getElementsByTagName('nav')[0]
.getElementsByTagName('a');
for(i in nav_anchors)
if(nav_anchors[i].href.match(/[A-z]+$/)[0] = page) //LINE 9 <-- Error
nav_anchors[i].classList.add('active');
})
})(this, this.document)
Thanks!
NodeLists have length, item and namedItem properties.
Use for (var i = 0; i < foo.length; i++) not for i in foo to iterate over them and only hit the nodes.
(function(window, document, undefined) { contentLoaded(window, function() {
var page = document.location.pathname.match(/[A-z]+$/)[0],
nav_anchors = document.getElementsByTagName('header')[0]
.getElementsByTagName('nav')[0]
.getElementsByTagName('a');
for(var i=0;i<nav_anchors.length;i++)
if(typeof nav_anchors[i].href != "undefined" && nav_anchors[i].href.match(/[A-z]+$/)[0] == page)
nav_anchors[i].classList.add('active');
})
})(this, this.document)
Added a check if the href of the anchor is set, in case you have page anchors without href attributes (Such as <a name="top"> called using #top). Added a second = in the IF for it to work as exepected. And corrected the for syntax.
if(nav_anchors[i].href.match(/[A-z]+$/)[0] = page) //LINE 9 <-- Error
In javaScript the equals sign = is an assignment operator. You probably mean double equals == where you can check values without type coercion (5 == "5") or triple equals === for strong typed checks (where 5 !== "5").
Sometimes document.location.pathname.match(/[A-z]+$/) can be null. If you try to use document.location.pathname.match(/[A-z]+$/)[0] you can not access the 0 Element of null.

Internet Explorer 7 - Javascript 'undefined' not testing

I'm having trouble with some JS in IE7. I'm testing to see if a certain object has a className (its possibly an HTMLElement object from the DOM) assigned.
Now, testing the page in Firefox tells me that Yes, the variable is undefined (all my tests below do the Alert().
In IE, none of the tests pass, the variable gets assigned on the last IF statement, and during the last Alert() IE chucks an "className is null or not an object" error, based on the fn_note.className statement.
Here's the code:
var fn_note;
var kids = area.childNodes;
for (var l = 0; l < kids.length; l++){
//DEBUG check if the found var exists
if (kids[l].className == null){
//then the className var doens't exist
alert ('the classsname for the following var is null: --'+kids[l]+'--');
}
if (kids[l].className == undefined){
//then the className var doens't exist
alert ('the classsname for the following var is undefined: --'+kids[l]+'--');
}
if (kids[l].className == ''){
//then the className var doens't exist
alert ('the classsname for the following var is an empty string: --'+kids[l]+'--');
}
if (typeof kids[l].className === 'undefined'){
//then the className var doens't exist
alert ('the classsname for the following var is NEW TYPEOF TEST: --'+kids[l]+'--');
}
if (kids[l].className == 'fn-note') { /* (/fn-note$/).test(kids[l].className) IE doesn't really like regex. por supuesto */
//we have found the div we want to hide
fn_note = kids[l];
}
}
alert('the clicked on className is '+area.className+'name of the found div is '+fn_note.className);
Please let me know what I am doing wrong. I know its probably something basic but I just can't see it ATM.
Thanks in advance.
I think that what you get from the property is not a string, but an object of the type 'undefined'. Try this:
if (typeof(kids[l].className) == 'undefined') {
As far as I can see the only thing you really want to know is if there's a childNode with className 'fn-note' in the childNodes collection. So do a somewhat more rigourous test:
for (var l = 0; l < kids.length; l++){
if (kids[l]
&& kids[l].className
&& kids[l].className.match(/fn\-note$/i)) {
fn_note = kids[l];
}
}
This should be sufficient (do mind escaping the dash in the regexp).

Is a JavaScript try-catch ignoring an expected occasional error bad practice?

In JavaScript is it wrong to use a try-catch block and ignore the error rather than test many attributes in the block for null?
try{
if(myInfo.person.name == newInfo.person.name
&& myInfo.person.address.street == newInfo.person.address.street
&& myInfo.person.address.zip == newInfo.person.address.zip) {
this.setAddress(newInfo);
}
} catch(e) {} // ignore missing args
If you expect a particular condition, your code will be easier to maintain if you explicitly test for it. I would write the above as something like
if( myInfo && newInfo
&& myInfo.person && newInfo.person
&& myInfo.person.address && newInfo.person.address
&& ( myInfo.person.name == newInfo.person.name
&& myInfo.person.address.street == newInfo.person.address.street
&& myInfo.person.address.zip == newInfo.person.address.zip
)
)
{
this.setAddress(newInfo);
}
This makes the effect much clearer - for instance, suppose newInfo is all filled out, but parts of myInfo are missing? Perhaps you actually want setAddress() to be called in that case? If so, you'll need to change that logic!
Yes. For one, an exception could be thrown for any number of reasons besides missing arguments. The catch-all would hide those cases which probably isn't desired.
I would think that if you're going to catch the exception then do something with it. Otherwise, let it bubble up so a higher level can handle it in some way (even if it's just the browser reporting the error to you).
On a related note, in IE, even though the specs say you can, you can not use a try/finally combination. In order for your "finally" to execute, you must have a catch block defined, even if it is empty.
//this will [NOT] do the reset in Internet Explorer
try{
doErrorProneAction();
} finally {
//clean up
this.reset();
}
//this [WILL] do the reset in Internet Explorer
try{
doErrorProneAction();
} catch(ex){
//do nothing
} finally {
//clean up
this.reset();
}
You could always write a helper function to do the checking for you:
function pathEquals(obj1, obj2, path)
{
var properties = path.split(".");
for (var i = 0, l = properties.length; i < l; i++)
{
var property = properties[i];
if (obj1 === null || typeof obj1[property] == "undefined" ||
obj2 === null || typeof obj2[property] == "undefined")
{
return false;
}
obj1 = obj1[property];
obj2 = obj2[property];
}
return (obj1 === obj2);
}
if (pathEquals(myInfo, newInfo, "person.name") &&
pathEquals(myInfo, newInfo, "person.address.street") &&
pathEquals(myInfo, newInfo, "person.address.zip"))
{
this.setAddress(newInfo);
}
For the example given I would say it was bad practice. There are instances however where it may be more efficient to simply trap for an expected error. Validating the format of a string before casting it as a GUID would be a good example.

Categories