1

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;

}
STF
  • 1,485
  • 3
  • 19
  • 36
mxjose100
  • 11
  • 1
  • 4
    This can't be all your code, I don't see `.addEventListener()` anywhere. – Spencer Wieczorek Oct 31 '16 at 05:08
  • `addEventListener` must be in code you **haven't** posted - try line 37 – Jaromanda X Oct 31 '16 at 05:08
  • 2
    Possible duplicate of [Cannot read property 'addEventListener' of null](http://stackoverflow.com/questions/26107125/cannot-read-property-addeventlistener-of-null) – Steve Oct 31 '16 at 05:08
  • 1
    Be aware: `document.getElementById('conversionResult');` will throw an error because your div in the html has a wrong id. – fatrex Nov 15 '17 at 08:51
  • In html document there are some typos, at line 4 must be `>` instead of `/>` and at line 7 to close the input tag you must use `>` istead of `/>`. Also if `document.getElementById` doesn't match a id tag that really exists in html document, it doesn't work. – Jul10 Nov 15 '17 at 09:28

1 Answers1

1

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:

CanProgram
  • 363
  • 2
  • 11