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.-
<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-
<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...
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With