Accesing a page element using JavaScript

Lately I feel like making a master about selectors but I promise this is only a coincidence. When working with javascript we need to select the element we want to use and we have many ways to do so, I was wondering which one is the better to use so I wondered and found an answer to this issue. Let’s see the alternatives:

alert(document.forms[0].elements[0].value);
alert(document.forms["myForm"].elements["myInputText"].value);
alert(document.myForm.myInputText.value);
alert(document.getElementById('myInputText').value);

The first option just moves across the document objects and knowing the position let us get the object we want with its value or other properties. This option is really risky since in case you change something in the page and add more forms or elements before the one selected it will not be at the same position anymore and you will get another object instead. What a bug you could make using this! No way I would use it.

The second option seems much more better, since it selects the forms and element not by its position but by its id. So it will continue working despite if you include more elements to the document. The bad point here could come in case you decide to move the element to another form or part of the page, in that case you would have the same problem as before.

The third option works the same way as the second one, maybe lighter and friendlier. Only have care with Firefox since this option uses the name attribute of the form instead of its id to find it.

The fourth one it’s surely the better option to use, it will find the element wherever it is, you don’t have to worry for its position, if it is on the page getElementByID will find it. Not only that, this is the W3C recommended way to do it, so its the standardized way to do it in a way that all follow standards browsers will recognize.

Leave a Reply

Close Bitnami banner
Bitnami