homepage Welcome to WebmasterWorld Guest from 54.211.235.255
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member

Visit PubCon.com
Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
Forum Library, Charter, Moderator: open

JavaScript and AJAX Forum

    
getElementById
id is null error
nyteshade




msg:4324996
 3:10 pm on Jun 11, 2011 (gmt 0)

I am trying to learn the flow of document load and rendering and where to place my js script and when to call it. So I have a page full of stuff but things are failing. I've narrowed down one error that I can not seen to figure out. The document.getElementById tells me the id is null and I'm not comprehending. I've been learning php, xml, css, mysql for the past year or so and I rarely have had to ask questions; but this js thing is a head-banger for me! Here's my failing js, please help.

<html>
<head><title>flow and forms</title>
</head>
<body>

<form id="form1"><p>This is form1.</p></form>
<form id="form2"><p>This is form2.</p></form>
<form id="form3"><p>This is form3.</p></form>

<script type="text/javascript">
for(var form in document.forms){
document.getElementById('docById').innerHTML= document.forms[form];
}
</script>

<div id="docById"></div>

<div>
<script>
for(var idx=0; idx<=document.forms.length; idx++){
document.write("<br />"+document.forms[idx].id);
}
</script></div>
</body>
</html>

The second script block works just fine and renders the ids of each
form. Thanks all!

 

Fotiman




msg:4325004
 3:22 pm on Jun 11, 2011 (gmt 0)

Your first script block is trying to access the element with id 'docById' before that element has been encountered in the DOM. Therefore, it does not exist when you are trying to access it.

Best practice is to place all of your scripts just before the closing </body> tag.

Note, your for loop is going to result in docById containing only the contents of the last form... is that what you were going for? If so, there are more efficient ways to do that. Like:

document.getElementById('docById').innerHTML = document.forms[document.forms.length - 1];

nyteshade




msg:4325019
 5:02 pm on Jun 11, 2011 (gmt 0)

Thanks for the reply. My intent is to wean myself off of document.write as my learning continues; and no, I really want to display all of the form ids in my empty div, not just the last one. I just had the code wrong. So I know to put certain script just before the </body> tag, thanks. Was hoping to have my code corrected by now but I'm still slogging on:

<html>
<head><title>flow and forms</title>
</head>
<body>

<form id="form1"><p>This is form1.</p></form>
<form id="form2"><p>This is form2.</p></form>
<form id="form3"><p>This is form3.</p></form>

<div id="docById"></div>

<script type="text/javascript">
var msg = "";
var idx = 0;
for(idx=0; idx<=document.forms.length; idx++){
msg += "<p>" + document.forms[idx].id + "<\/p>";
}
document.getElementById('docById').innerHTML= msg;
</script>
</body>
</html>


Error is: document.forms[idx] is undefined. I understand what you said about the DOM and placement of script but it's the execution order or declaration order that I'm not getting?

lucy24




msg:4325045
 6:44 pm on Jun 11, 2011 (gmt 0)

for(idx=0; idx<=document.forms.length; idx++)
{
msg += "<p>" + document.forms[idx].id + "<\/p>";
}


Check document.forms.length and verify that it has a non-zero value, since the loop depends on it.

JAB Creations




msg:4325086
 8:59 pm on Jun 11, 2011 (gmt 0)

Don't use innerHTML either, it's a completely unreliable proprietary Microsoft method and it's does not work with the DOM or XHTML even if it sometimes looks like it might be working. Take it from someone who works with a lot of AJAX with a exceptionally high need for reliability. ;)

With JavaScript you can use object detection to determine if something such as a form field exists...

if (document.getElementById('my_id')) {alert(document.getElementById('my_id').value);}


- John

nyteshade




msg:4325106
 11:10 pm on Jun 11, 2011 (gmt 0)

Okie-dokie. All I needed to hear was that innerHTML is MS proprietary and now I'm completely off it. I'm at [slayeroffice.com...] which appears to be giving me the skinny on some excellent DOM stuff. However, that brings me back to my UNDEFINED var problem. I've cut out the getElementById example and I'm back to document.write until I get through the DOM tutorial. So, from my simple example below, I still get "document.forms[idx] is undefined" from the error console in FF even though the code rendors the page correctly. I'm trying to understand the flow of the code, hmmm is it a scope problem? I hate going forward without full comprehension.

<html>
<head><title>flow and forms</title>
</head>
<body>

<form id="form1"><p>This is form1.</p></form>
<form id="form2"><p>This is form2.</p></form>
<form id="form3"><p>This is form3.</p></form>


<script type="text/javascript">
var idx=0;
if(document.forms.length !==0){
for(var idx=0; idx<=document.forms.length; idx++){
document.write("Form: " + idx + " is " + document.forms[idx].id + "</p>");
}
}
</script>
</body>
</html>

nyteshade




msg:4325285
 9:13 pm on Jun 12, 2011 (gmt 0)

Nevermind, I got it, test condition should be < only, mea culpa. Too much coffee and not enuff sleep. Peace.

Fotiman




msg:4325302
 11:29 pm on Jun 12, 2011 (gmt 0)

innerHTML WAS a Microsoft proprietary method, but has been adopted by all the current browsers, and has been standardized and included in HTML5. It is very reliable.

lucy24




msg:4325314
 12:54 am on Jun 13, 2011 (gmt 0)

innerHTML WAS a Microsoft proprietary method, but has been adopted by all the current browsers, and has been standardized and included in HTML5.

It works on all five browsers on my Mac, and on MSIE 6, which doesn't leave a lot of browsers for it not to work on :) (I didn't deliberately go out and experiment. I went back, looked at a file and found that my font-search routine uses it. Which is pretty funny when you think about it.)

JAB Creations




msg:4325343
 4:11 am on Jun 13, 2011 (gmt 0)

Lots of coincidences of late...
[slayeroffice.com...]

Again I'll reiterate, innerHTML does not properly (or perhaps at all) "register" DOM nodes, it simply dumps HTML in to place. In example if you try to use JavaScript with (X)HTML that was loaded via AJAX and dumped on to the page via innerHTML you can't give focus and scripts might work. Might doesn't count here.

- John

nyteshade




msg:4325396
 10:28 am on Jun 13, 2011 (gmt 0)

In my mind I'm inclined to suspect innerHTML because it's too easy to use; that's just my gut talking. My head is suspicious because it's just a string. And now that I've cursorily reviewed the DOM way of things, my intuition tells me that XML, a subset of SGML, the grand-daddy of markup, and HTML and DOM (that follow the way of XML) fit together nicely like pieces of a puzzle; innerHTML does not.

It may be 'adopted', but it may be that orphan mutant thing that over time will bite the hand that feeds it. I'm still new at this web development stuff, but I'm trying to stay on a well-formed path and not get side-tracked by easy appearing solutions.

Since I don't use an IDE (I use Notepad++) I plan on using document.write for debugging and I guess innerHTML could be used to dump text into a divisible element for debugging too.

Fotiman




msg:4325439
 1:11 pm on Jun 13, 2011 (gmt 0)


In example if you try to use JavaScript with (X)HTML that was loaded via AJAX and dumped on to the page via innerHTML you can't give focus and scripts might work.

Here is a test case that disproves that claim:

<!DOCTYPE html>
<html>
<head>
<title>innerHTML test</title>
</head>
<body>
<div id="container"></div>
<script>
var container = document.getElementById('container');
container.innerHTML = "<div id='mydiv'><input id='foo'><\/input><input type='button' id='btn' value='click me'><\/input><\/div>";
var btn = document.getElementById('btn');
var foo = document.getElementById('foo');
btn.onclick = function () {
foo.focus();
foo.value = "This works just fine.";
}
</script>
</body>
</html>

In this example, the HTML/DOM is modified by using innerHTML. And then one of the DOM nodes is retrieved and focus can be set on another element that was also added via innerHTML.

Fotiman




msg:4325440
 1:17 pm on Jun 13, 2011 (gmt 0)


In my mind I'm inclined to suspect innerHTML because it's too easy to use

That's a bit like saying "Even though it works fine, I'm not going to use email because it's a bit too easy... instead I'm going to send all messages via snail mail." Don't knock something because it's easy to use. :)


I plan on using document.write for debugging

Since you are just learning, you should also read up on why document.write should be avoided. I'll take innerHTML over document.write any day.

Fotiman




msg:4325444
 1:21 pm on Jun 13, 2011 (gmt 0)

Also, one more thing I want to clarify...
If you are writing XHTML documents that are being served as application/xhtml+xml (vs. being served at text/html), then I would agree that you should choose DOM methods for inserting content. However, there are very few cases that actually warrant using XHTML. If you're serving HTML content and not extending the language in any way, then serve it as HTML.

nyteshade




msg:4325930
 1:58 pm on Jun 14, 2011 (gmt 0)

Thanks Fotiman for the clarification. My XHTML files really reflect XHTML compliant elements. I've been using STRICT to get in the habit of writing XHTML compliant elements not necessarily XML apps. I understand the difference. My XML is limited to writing DTD's and XML files that use them, remember, I'm a nube just taking it step-by-step. BTW - I just discovered Firebug lets me step through javascript, what a relief, document.write was such a headache!

susky




msg:4326508
 6:08 pm on Jun 15, 2011 (gmt 0)

The innerHTML have been adopted by all browsers and using innerHTML is very fast and easy.

you should use: for var i=0;i<obj.length;i++

should not use :for in

JAB Creations




msg:4327154
 2:43 am on Jun 17, 2011 (gmt 0)

The vast majority of HTML will not work if converted to XHTML whereas most if not all XHTML will still work is converted to HTML.

When working with JavaScript I highly recommend using Opera's JavaScript/error console. I've noticed that Firefox doesn't report all scripting errors for some reason. For IE7 and older there is a JavaScript developer tool that you can download that is almost on par with the developer tools in IE8. WebKit browsers have the inspector tool which is useful too. All of them have their respective strengths and weaknesses and I generally recommend using them all to make sure your scripts are well written and bug free.

Fotiman, do you remember that thread that ended up being featured on the front page a few months ago? Someone there ended up clarifying what the problem with innerHTML was.

- John

Fotiman




msg:4327165
 3:29 am on Jun 17, 2011 (gmt 0)

I remember talk of it, but don't remember what the issue was (I've been in so many threads, I lose track of which issues were discussed where). :)

JAB Creations




msg:4327886
 9:51 pm on Jun 18, 2011 (gmt 0)

*looks at Foti's post count* Yeah, I got to work off this flab! :)

- John

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved