6

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!

Zee
  • 8,420
  • 5
  • 36
  • 58
Cam C
  • 61
  • 1
  • 1
  • 2

2 Answers2

7

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.

jAndy
  • 231,737
  • 57
  • 305
  • 359
  • 3
    Thanks guys, it's sorted. It was a silly mistake. I put my script link before the id tag in the html. So the "breakf" didn't exist at the time the script was run. Thank you for your help! – Cam C Apr 25 '15 at 11:08
  • @CamC I think it would be useful if you write your comment as an answear. There are a lot of other silly people around the world. (Which includes me...) – basti12354 Nov 26 '16 at 14:27
1

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();