Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

document.object Vs. document.getElementById()

Tags:

javascript

What is the difference between these two syntaxes below-

document.object and document.getElementById().

I want to know when to use which syntax???

e.g.-

CODE1(Implementation with <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 the syntax in onload works the same way. But this doesn't work for the following-

CODE2(Implementation with <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 definitely the syntax: document.object does not work with <div>-elements but works with <form>'-element. But **document.getElementById()`** works for both. So when should I use which one???

Someone please highlight the differences between the two syntaxes.

Thanx in advance...

like image 990
Rajesh Paul Avatar asked Oct 03 '13 15:10

Rajesh Paul


2 Answers

you can use document.object_name to find anchors, applets, embeds, forms, images, links, plugins.

to find HTML Elemets like div, span, etc. you have to use selectors. you can get this elements by element name, id, class, etc.

like image 20
Ghanshyam Bhalala Avatar answered Sep 22 '22 21:09

Ghanshyam Bhalala


document.forms is a very old method of accessing stuff, along with document.images and document.all, and possibly a few others that I don't remember.

The number one flaw in accessing document.forms[1] is simple: what if another form is added to the page, before the target one? Suddenly you have to search through all your code for references to anything, and change them.

This is where IDs come in. By only allowing one of each ID on a page, getElementById can accurately retrieve it, every time, without caring about what happens to the document in the meantime. The only change that matters is the element being removed altogether.

like image 146
Niet the Dark Absol Avatar answered Sep 21 '22 21:09

Niet the Dark Absol