JS error message textContent is set to null

I'm new to JS and the world of web development, so apologize in advance if my question is a little tedious.

I wrote this code:

var breakfast = new Object();
breakfast.food = "croissant";
breakfast.extra = ["mushroom", "cheese"];
breakfast.eat = function(){return this.food + " with " +  this.extra[0];}
var elBreakfast = document.getElementById("breakf");
elBreakfast.textContent = breakfast.eat();


I am getting an error from the browser:

"Uncaught TypeError: Cannot set property 'textContent' of null"... 


What I did wrong?



source to share

3 answers

The only important code here is document.getElementById("breakf");

. It seems that your browser is unable to request an element with an ID breakf

in your HTML markup.

Therefore, you need to validate your live HTML in your browser. Check if there is HTML node with id=breakf

. If not, you should get this error correctly.



Try adding a script referenced to the end of the body tag in your html page so that it loads the breakf element and then applies the breakfast.eat () method;



The error comes from document.getElementById("breakf")

here. The browser cannot find the node with the ID breakf


Check your html code for node with id="breakf"

, if it's not there, add it to the node you want to write to text and it should be good.



All Articles