mxjose100
mxjose100

Reputation: 11

Celsius conversion

I'm doing a homework packet for school and I don't know how to fix this error:

Uncaught TypeError: Cannot read property 'addEventListener' of null

It's a simple problem, all I have to do is convert celcius to fahrenheit.

HTML

<body>
    <h3>Enter the temperature in celcius</h3>
    <ul>
        <li>Temp in celcius<input type="text" id="celcius" />
    </ul>
    <div>
        <input type="button" value="convert" onclick="converter()"/>
    </div>
    <span id="conversion result"></span>

    <div id="tempConverter"></div>
    <span id="celciusT"></span>
    <script src="../js/JavaScript.js"></script>
</body>

JavaScript

function converter() {
    var celcius = document.getElementById('celcius');
    var conversionResult = document.getElementById('conversionResult');

    conversionResult.textContent = celcius.value * 9 / 5 + 32;

}

Upvotes: 1

Views: 161

Answers (1)

CanProgram
CanProgram

Reputation: 373

It doesn't work because you're referencing a non-existent ID. Your HTML element has an illegal space in the ID:

<span id="conversion result"></span>

while your script uses camelCase to refer to the ID:

var conversionResult = document.getElementById('conversionResult');

I recommend picking a convention and sticking to it. I strongly discourage using camelCase for IDs (you can use it for JS if you want though). Hyphen-separated names are the most common convention, while underscore-separated names are also a valid approach.

Check out: Google HTML/CSS Style Guide and BEM


Using spaces in IDs will only lead to trouble. Check out the HTML 4.0 specification for basic types:

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").


StackOverflow questions:

Upvotes: 1

Related Questions