james.1qwrnewkbjrkwj james.1qwrnewkbjrkwj - 3 months ago 16
HTML Question

Javascript cannot select innerHTML by class name

I am just trying to select HTML object and set the inner text but I am getting these errors

greeter.js:

function greet(person) {
return "Hello, " + person;
}
var user = "AAA";
document.getElementsByClassName('greet')[0].innerHTML = greet(user);


HTML:

<!DOCTYPE html>
<html>

<head>
<title>TypeScript Greeter</title>
</head>

<body>
<script src="greeter.js"></script>
<p class="greet"></p>
</body>

</html>


This error

Uncaught TypeError: Cannot set property 'innerHTML' of undefined


Setting
document.getElementsByClassName('greet')[0].innerHTML = "a"
directory works, but when I try to set it with function, it doesn't work.

Answer

Try swapping the order of:

<script src="greeter.js"></script>
<p class="greet"></p>

to:

<p class="greet"></p>
<script src="greeter.js"></script>
Comments