Debugging in Javascript - The Hard Way
(Page 2 of 5 )
If there is a situation where you can't use Mozilla or Venkman for your development, you will have to do things the hard way. Internet Explorer and Firefox both have a way to display Javascript errors, which will sometimes help. Apple's Safari also has this feature, using a separate application. Neither browser will help you if there are no syntax errors in your code. If you are trying to figure out why the wrong data is being written, or a number isn't right for instance, you're out of luck.
The most common method for debugging code in the browser is to use the alert box. It can be used to display variable contents, object names and types and loop counters. Unlike the way a debugger works however, you must write the alert function into your code.
For instance, say you are trying to determine if you have a comment before a paragraph and if you do, you want to add a second comment in the source before the paragraph. For some reason the "if" construct is not evaluating. Use the alert() function to bring up a dialog box that shows you the value for which you are supposed to be checking.
function process(pName,addedText)
{
var paragraph = document.getElementById(pName);
alert(paragraph.previousSibling.nodeName);
if(paragraph.previousSibling.nodeName == "comment")
{
paragraph.parentNode.insertBefore(document.createComment(text),paragraph);
}
}
So what's the problem? Well, as you can see in the screen shot, the dialog shows that the nodeName property for a comment tag in this browser (Firefox) is "#text" which means it is being parsed as a text node. You might not know this if you're used to working with the nodeName properties of other tags, such as a paragraph tag, which is simply "p." if you changed the if construct to look for "#text" it would evaluate properly.
Please note that, curiously, if you create a comment as we did above and check its node name property, it will come up as "#comment." Only comments that were in the source to start with come up as "#text," if indeed they come up at all. Comments are a node type, but they are apparently not parsed as such by most user agents when the document is loaded.
Next: Using Comments >>
More JavaScript Articles
More By Chris Root