Ramzi Khahil
Ramzi Khahil

Reputation: 5072

Accessing HTML DOM elements from javascript using `.childNodes`

I'm wondering about the .childNodes property, I have the code below, and for some reason I get 18 children, while 6 are HTMLInputElements as expected, and the rest are undefined. What is this about? Is there an efficient way to iterate over the input elements?

<html>
  <head>
    <script>
    window.onload = function(e){
        form = document.getElementById('myForm');
        alert(form.childNodes.length);
        for(i=0; i<form.childNodes.length; i++){
            alert(form[i]);
        }
    }
    </script>
  </head>
  <body>
<form id='myForm' action="haha" method="post">
Name: <input type="text" id="fnameAdd" name="name" /><br />
Phone1: <input type="text" id="phone1Add" name="phone1" /><br />
Phone2: <input type="text" id="phone2Add" name="phone2" /><br />
E-Mail: <input type="text" id="emailAdd" name="email" /><br />
Address: <input type="text" id="addressAdd" name="address" /><br />
<input type="submit" value="Save" />
</body>
</html>

Upvotes: 1

Views: 1322

Answers (4)

Marat Tanalin
Marat Tanalin

Reputation: 14123

Use form.elements to get all form fields, or form.getElementsByTagName('INPUT') to get INPUT elements inside the form.

Upvotes: 1

kennebec
kennebec

Reputation: 104840

form.elements is the quick way to access every element of a form-

window.onload = function(e){
        var s='', form = document.getElementById('myForm'),
        L=form.elements.length;
        s=L+'\n';
        for(var i=0;i<L; i++){
            s+= (form[i].name || form[i].id)+'='+form[i].value+'\n';
        }
        alert(s);
    }

Upvotes: 0

user1106925
user1106925

Reputation:

Text nodes, even if they consist only of whitespace, will also be included in the output, as will the br elements.

Use .children instead if you want all the elements, including br. This will give you element nodes only. I think older IE incorrectly includes comment nodes, but you have none in your code, so no issue.

Or you could do...

form.getElementsByTagName('input')

...assuming you only wanted the input elements.

And besides that: you forgot to close your form element.

Upvotes: 3

machineghost
machineghost

Reputation: 35725

childNodes also returns text nodes; this is probably the source of your confusion.

To iterate through all the childNodes, but only pay attention to the INPUTs, simply check the node's tagName property. If the node is a text node it won't have a tagName, and if the node does have a tagName you can check whether tagName == "input".

Upvotes: 1

Related Questions