Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS error message textContent set as null [duplicate]

Tags:

javascript

I am fairly new to JS and the world of web development, so apologise in advance if my question is a bit 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 get an error message from the browser:

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

What have I done wrong?

Thanks!

like image 858
Cam C Avatar asked Apr 24 '15 09:04

Cam C


3 Answers

The only important code here is document.getElementById("breakf");. It seems like your browser is unable to query for the element with an ID of breakf within your HTML markup.

So you need to check your HTML code live in your browser. Check if there is any HTML node with id=breakf. If not, you correctly should receive that error.

like image 134
jAndy Avatar answered Oct 23 '22 21:10

jAndy


Try to add script reference end of body tag in html page so that it will load breakf element and then applies the breakfast.eat();

like image 1
Bhanuprathap Bussa Avatar answered Oct 23 '22 21:10

Bhanuprathap Bussa


The error is coming from document.getElementById("breakf") here. The browser can't seem to find a node with an id of breakf.

Check your html code for a node with id="breakf", if it's not there, add it to the node you want to write text in and it should be good.

like image 1
Lilian Tedone Avatar answered Oct 23 '22 23:10

Lilian Tedone