Search code examples
javascripthtmlnodevalue

Cannot set property 'nodeValue' of null


I'm going through a book and it seems to be right, but the following code keeps giving me the error: Cannot set property 'nodeValue' of null. The code makes sense to me, but I don't understand why it can't clear the text value when clicking the clear button.

var clear = function(){

        $("miles").firstChild.nodeValue = "";
        $("gallons").firstChild.nodeValue = "";
        $("mpg").firstChild.nodeValue = "";
         }

    window.onload = function () {
        $("calculate").onclick = calculateMpg;
        $("miles").focus();
        $("clear").onclick = clear;
    }   

Html

<section>
    <h1>Calculate Miles Per Gallon</h1>
    <label for="miles">Miles Driven:</label>
    <input type="text" id="miles"><br>
    <label for="gallons">Gallons of Gas Used:</label>
    <input type="text" id="gallons"><br>
    <label for="mpg">Miles Per Gallon</label>
    <input type="text" id="mpg" disabled><br>
    <label>&nbsp;</label>
    <input type="button" id="calculate" value="Calculate MPG"><br>
    <input type="button" id="clear" value="clear"><br>
</section>

Solution

  • Input elements do not have child nodes so firstChild gives you null, further more if you're trying to clear the value of the input fields use the value property.

    var clear = function(){
        $("miles").value = "";
        $("gallons").value = "";
        $("mpg").value = "";
    }