Why is the childNodes giving me text before input element when I console.log the parent?

Why when I console.log the parent's childNodes it gives me this 'text' as one of their childNode?

How can I overcome it?

 <div id="inputDiv">
        <input type="text" id="name" placeholder="Enter the name">
        <input type="text" id="age" placeholder="Enter the age" >
        <input type="radio" name="gender" value="male" checked> Male
        <input type="radio" name="gender" value="female">Female
        <input type="text" id="language" placeholder="Enter the language" >
        <input type="text" id="empid" placeholder="Enter a employeeId" disabled>
        <input type="text" id="salary" placeholder="Enter the salary" >
        <input type="text" id="experience" placeholder="Enter experience" >
        <select id="employeesType" onchange="ChangeEmployeeType()">
            <option value="manager">Manager</option>
            <option value="staff">Staff</option>
        </select>
        <input type="text" id="managerName" placeholder="Enter the manager name">
        <button id="addPerson" onclick="addPerson()">Person</button>
    </div>

When I console.log(getElementById("inputDiv").childNodes); it produces:

Actual Result :

NodeList(23) [text, input#name, text, input#age, text, input, text, input, text, input#language, text, input#empid, text, input#salary, text, input#experience, text, select#employeesType, text, input#managerName, text, button#addPerson, text]

Expected Result :

NodeList(23) [text, input#name, text, input#age, text, input, text, input, text, input#language, text, input#empid, text, input#salary, text, input#experience, text, select#employeesType, text, input#managerName, text, button#addPerson, text]

Upvotes: 2

Views: 662

Answers (1)

quirimmo
quirimmo

Reputation: 9988

In HTML text elements are actually node elements.

Use children if you want only the "real elements" and create an array from them if you need an array of these elements:

console.log(Array.from(document.getElementById("inputDiv").children));
<div id="inputDiv">
  <input type="text" id="name" placeholder="Enter the name">
  <input type="text" id="age" placeholder="Enter the age">
  <input type="radio" name="gender" value="male" checked> Male
  <input type="radio" name="gender" value="female">Female
  <input type="text" id="language" placeholder="Enter the language">
  <input type="text" id="empid" placeholder="Enter a employeeId" disabled>
  <input type="text" id="salary" placeholder="Enter the salary">
  <input type="text" id="experience" placeholder="Enter experience">
  <select id="employeesType" onchange="ChangeEmployeeType()">
    <option value="manager">Manager</option>
    <option value="staff">Staff</option>
  </select>
  <input type="text" id="managerName" placeholder="Enter the manager name">
  <button id="addPerson" onclick="addPerson()">Person</button>
</div>

Upvotes: 3

Related Questions