Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

document.getElementById fails for single-tag DIV

I have 2 DIVs on an HTML page:

<div id="divDebug" />
<div id="divResult" />

I have a script that hits a web service and fills them up with data:

document.getElementById("divDebug").innerHtml = rawResult;
document.getElementById("divResult").innerHtml = processResult(rawResult);

Here's my problem:

  1. The above code works nicely in IE 8
  2. The above code sometimes works and sometimes doesn't in Chrome 3.
  3. Only the first line works in FF 3.51. Upon testing with FireBug, I can see that the expression document.getElementById("divResult") evaluates to null.

After much trial and error, I found out that if I change the HTML code to:

<div id="divDebug"></div>
<div id="divResult"></div>

Everything works well in all 3 browsers.

My questions are:

  1. Why do I have to close the DIVs in order for them to be available?
  2. Is this a JavaScript thing, or an FF bug?
  3. Are there any other HTML elements that will become unavailable if they are not closed properly?

Thanks!

like image 594
Traveling Tech Guy Avatar asked Dec 10 '25 15:12

Traveling Tech Guy


1 Answers

<div/> is the XML way of closing tags, basically. <div></div> is HTML (and XML).

What DOCTYPE are you using?

From C. HTML Compatibility Guidelines in XHTML™ 1.0 The Extensible HyperText Markup Language (Second Edition):

C.3. Element Minimization and Empty Element Content

Given an empty instance of an element whose content model is not EMPTY (for example, an empty title or paragraph) do not use the minimized form (e.g. use <p> </p> and not <p />).

like image 63
cletus Avatar answered Dec 12 '25 05:12

cletus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!