1

this is my code :

<body>
     <p id="x"></p>
     <p id="y"></p>
    <form action="2.php" method="post" name="frm">
        <input type="text" name="srch">
    </form>
    <script>
        obj = document.forms["frm"]["srch7"];
        obj1 = document.getElementById("noexist");
        document.getElementById("x").innerHTML = obj;
        document.getElementById("y").innerHTML = obj1;
    </script>
</body>

why obj return undefined but obj1 return null, document.forms["frm"]["srch7"]; and document.getElementById("noexist"); both are object and must return null,because elements no exist.

Ehsan
  • 12,655
  • 3
  • 25
  • 44

4 Answers4

3

Both cases are different,

obj = document.forms["frm"]["srch7"];
//Here you are trying to access a property that 
// is not present under document.forms.frm.

obj1 = document.getElementById("noexist");
//Here it is returning null because getElementById implemented in that way.
// getElementById will return null if the DOM search didn't find any element
// based on the supplied id.
Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
2

Because form with the id frm exists, and its property srch7 is undefined, means not defined. But in case when you are trying to get element by id noexist that element is null, or it doesn't exist.

Senad Meškin
  • 13,597
  • 4
  • 37
  • 55
  • 1
    *document.getElementById* is required to return *null* by the related specification: [*W3C DOM Level 4*](http://www.w3.org/TR/dom/#dom-nonelementparentnode-getelementbyid). – RobG May 05 '16 at 09:57
1

Because, here you are trying to get the object/element from the dom and if it doesn't find the object/element it returns object's empty default value i.e. null

obj1 = document.getElementById("noexist");

And here you are trying to get the value of a field (not the object) and if it doesn't find any value assigned to that field or variable it retuns undefined.

undefined means a variable has been declared but has not yet been assigned a value

obj = document.forms["frm"]["srch7"];

See this post What is the difference between null and undefined in JavaScript?

Community
  • 1
  • 1
Pawan Nogariya
  • 8,330
  • 12
  • 52
  • 105
0
 obj = document.forms["frm"]["srch7"];
 obj1 = document.getElementById("noexist");
  • Here for obj document.forms["frm"] is null so the property of any null object is undefined.
  • And for obj1 the value of document.getElementById("noexist"); is null.
  • So these are the difference between these two objects.
Chetan Sanghani
  • 2,058
  • 2
  • 21
  • 36