Document.object Vs. document.getElementById ()

What is the difference between these two syntaxes below -

document.objectand . document.getElementById()

I want to know when to use which syntax

.- eg

CODE1 (Implementation c <form>)

<body onload="document.forms[1].innerHTML='hi';">//Alt: onload="document.getElementById('f1').innerHTML='hi';"
<form id=f1>
    <input />
</form>
<form id=f2>
    <input />
</form>
</body>

both syntaxes onloadwork the same way. But this does not work for the following -

CODE2 (Implementation c <div>)

<body onload="document.getElementById('div1').innerHTML='hi';">//cannot use the syntax: onload="document.divs[1].innerHTML='hi';"
<div id=div1>hello</div>
<div id=div2>hello</div>
</body>

So the syntax is definitely: does not work with -elements, but works with document.getElementById () `** works for both. So when should I use some ??? document.object<div><form>'-element. But **

Someone please highlight the differences between the two syntaxes.

Thanx in advance ...

+4
source share
3 answers

document.forms - , document.images document.all , , , .

document.forms[1] : , , ? - .

. , getElementById , , . , , - , .

+3

document.object_name, , , , , , , .

HTML Elemets, div, span .., . , id, ..

+1

The easiest way to access the div in your example is through the "named access on window object" function ( http://www.whatwg.org/specs/web-apps/current-work/#named-access-on-the- window-object ):

Instead

<body onload="document.getElementById('div1').innerHTML='hi';">

you can use

<body onload="div1.innerHTML='hi';">

Note that "div1" is a property of the window object, not a document object.

0
source

All Articles