james.1qwrnewkbjrkwj james.1qwrnewkbjrkwj - 1 year ago 63
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


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


<!DOCTYPE html>

<title>TypeScript Greeter</title>

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


This error

Uncaught TypeError: Cannot set property 'innerHTML' of undefined

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

Answer Source

Try swapping the order of:

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


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