-1

Trying to add content into individual div-containers I stumbled on the command .innerHTML, which I tried to implement accordingly. Strangely I get the following error:

*Uncaught TypeError: Cannot read property 'innerHTML' of null *

I'm running the code over my local Apache server if that makes any difference.

index.html

<html>
  <head>
    <title>Welcome</title>
    <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
    <script type="text/javascript" src="javascript.js"></script>
    <link rel="stylesheet" href="style.css">
  </head>
  <body>
  <div id="header">
  <h1>Startseite</h1>
  </div>
  <div id="container">
    <div id="left">
        Navigation
    </div>
    <div id="content"></div>
    <div id="right"></div>
    <div class="clr"></div>
  </div>
  </body>
</html>

javascript.js

var navidiv = document.getElementById('left');
navidiv.innerHTML += "FirstElement"; 
Fabitosh
  • 41
  • 8
  • Aye, as with below answers, you must wait for the DOM to load. This is why I always put my scripts at the end of the body. – ndugger May 07 '14 at 12:35
  • possible duplicate of [Why does jQuery or a DOM method such as \`getElementById\` not find the element?](http://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – Felix Kling May 07 '14 at 13:05

3 Answers3

1

Put it in window.onload

window.onload = function()
   var navidiv = document.getElementById('left');
   navidiv.innerHTML += "FirstElement"; 
}

The element has to be present in the DOM, before you can access it in JS

Amit Joki
  • 53,955
  • 7
  • 67
  • 89
1

You have to ensure that your DOM elements have loaded before accessing them with javascript.

Since you are using jquery, your javascript can simply be

$(function() {
  var $navidiv = $('#left');
  $navidiv.html($navidiv.html() + 'FirstElement');
});
Daniel A. White
  • 174,715
  • 42
  • 343
  • 413
0

try this

html

<div id="header">
  <h1>Startseite</h1>
  </div>
  <div id="container">
    <div id="left">
        Navigation
    </div>
    <div id="content"></div>
    <div id="right"></div>
    <div class="clr"></div>
  </div>

javascript.js

$( document ).ready(function() {
    var navdiv=$("#left").html();
    $("#left").html(navdiv+"FirstElement");
});

see DEMO

Boopathi Rajan
  • 1,144
  • 12
  • 36