Question

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>
Was it helpful?

Solution 2

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 = "";
}

OTHER TIPS

I think what you want is this where you use the .value property on the input fields directly:

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

Here's an explanation of what was going on. Now that we can see your full page and see that $ is document.getElementById(), the issue is that you are some of those nodes don't have a firstChild.

For example the object with an id="miles" is an input tag and it has no children so .firstChild is null.

In this line:

$("miles").firstChild.nodeValue = "";

$("miles") gets you the DOM object.

$("miles").firstChild returns null because there are no children of that DOM object.

$("miles").firstChild.nodeValue = ""; is an error because $("miles").firstChild is null and null doesn't have a property .nodeValue.

Looking at the code you posted in the comments, the problem is that $("miles") and the other elements don't have any children.

It seems like you're trying to do something like this:

var clear = function() {
    $("miles").value = "";
    $("gallons").value = "";
    $("mpg").value = "";
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top