Why does getElementById() returns null (to an existing id)?

Hi, there.
Why does the code below returns a message on the console “pNode is null”, and not a reference to the element with id=“pNodeId”?
What could be going wrong?

function pClick(event) {
	alert("Click on p.");
}
var pNode = document.getElementById("pNodeId");
pNode.addEventListener("click", pClick);

Hint.: the id of the element (pNodeId) is strictly orrect.

Thanks in advance!

Can you show us the HTML the JS is targeting? Where is the JS file being linked - in the <head>, or just before the closing <body> tag?

Sure, there it goes:

===

!doctype html>
<html>
<head>
	<meta charset="utf-8">
	<title>Events examples</title>
	<link rel="stylesheet" href="styles.css">
</head>

<body>
<h1>Events!</h1>
<hr>
<script>
	function pClick(event) {
		alert("Click on p.");
	}
	var pNode = document.getElementById("pNodeId");
	pNode.addEventListener("click", pClick);
</script>
<p id="pNodeId">A text in events_3.html ok</p>

</body>
</html>

===

Thanks!

I see the problem, the <script> section needs to be after the HTML with the ID you’re targeting. The script is running before its been loaded, so it can’t find the ID it’s looking for.

1 Like

Worked just fine.
Thank you very much!
:slight_smile:

But… it could also be placed into the head tag (either the link or the code), is that so?
Thanks again

Is the head tag after the p tag? No? Well then you’ll have a problem.

The alternative is to wrap your code on a listener for when the page is done loading…

document.addEventListener("DOMContentLoaded", function(event) {
   //Your stuff
}

Which then allows you to put your code anywhere on the page, since it waits for the page to load before executing.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.