kuriouscoder
kuriouscoder

Reputation: 5582

Accessing DOM information on the web

I am new to document object model. Is there any java-doc like thing for DOM. I am having tough time figuring out the following javascript code.

myElements = document.getElementById('idName').elements // whose attribute is elements part of ? Element Object or Node?
for (var eachElement in myElements) {
    if (myElement[eachElement].type == 'checkbox' ) {
        // why do I have to do this? Specifically, why can't type be accessed as eachElement.type == 'checkbox'
     }
 }

I think the bigger problem is I am having tough time in accessing documentation. Any clues on both would be appreciated.

Upvotes: 4

Views: 84

Answers (3)

Felix Kling
Felix Kling

Reputation: 817228

As already mentioned, the MDC documentation is quite comprehensive.

// why do I have to do this? Specifically, why can't type be accessed as eachElement.type == 'checkbox'

.elements returns a HTMLCollection [docs]. This is an array-like data structure which can be traversed via a for or for...in [docs] loop.

for...in loops over properties of objects. The property name (the index, so to speak, not its value) is stored in the loop variable, hence, to access the corresponding value, you have to write obj[prop].

That is also the reason why you should not use for...in here. You don't know whether it also loops over other properties of the collection that are not elements.

Use a normal for loop:

var myElements = ...;
for(var i = myElements.length; i--; ) {
    var element = myElements[i];
    //...
}

I suggest to also read the JavaScript guide to learn more about loops, arrays and objects.

Upvotes: 2

Jason Gennaro
Jason Gennaro

Reputation: 34863

Here's what it says:

myElements = document.getElementById('idName').elements 
//Find the form with the id="idName"
//and gather all the form elements in an object/array

//because there could be more than one element in the form, 
//you will need to loop through the object

//loop now and for each element that is a checkbox
//do the following, where it says DO SOMETHING

for (var eachElement in myElements) {
    if (myElement[eachElement].type == 'checkbox' ) {

    //DO SOMETHING

     }
 }

Upvotes: 0

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196296

.elements property exists only for form elements https://developer.mozilla.org/en/DOM/HTMLFormElement

So in your case, the idName has to point to a form element with id="idName", otherwise it would cause an error.

The elements property will return a collection of form controls. https://developer.mozilla.org/en/DOM/form.elements

Upvotes: 2

Related Questions