Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 711
oxxi Avatar asked Apr 22 '26 12:04

oxxi


1 Answers

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.

like image 122
jfriend00 Avatar answered Apr 25 '26 01:04

jfriend00



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!