ejshin1
ejshin1

Reputation: 1167

Uncaught TypeError: Cannot set property 'innerHTML' of null [] even though div exists

I am trying to set property of HTML with div and it throws an error saying "cannot set property 'innerHTML' of null.

In JavaScript,

function find_person() {

    ...

    var title = 
    "<div class=\"w3-container\">" +
    "<h3>Find a person</h3>";
    "</div>";

    document.getElementById("content_title").innerHTML = title;
}

In HTML,

<div id="content" class="w3-display-container w3-container">
    <div id = "content_title" class = "w3-row" >Title goes here
    </div>
    <div id= "content_main" class = "w3-row">
    </div>
</div>

Could you help me figure out what causes an error of recognizing div?

Upvotes: 1

Views: 526

Answers (4)

blaise johnny
blaise johnny

Reputation: 13

Make sure that in the html, you put your "Script" Tag anywhere under the you're looking for or even best all the way under the 's closing tag. When javascript asks for id's and/or classes from its parent folder for manipulation it looks from top to where it's initialized not below. :D

Upvotes: 0

Colin Cline
Colin Cline

Reputation: 1279

its simple with jQuery library (if you need pure js please clarify that in title)

html code:

<a href="#" class="specific-button">button</a>

js code:

function find_person(){
   var title = '<div class="w3-container">'+
                  '<h3>Find a person</h3>'+
                '</div>';

   jQuery("#content_title").html(title);
}

jQuery(document).ready(function(){
    jQuery('a.specific-button').on('click', function(e){
        e.preventDefault();// this will prevent button to refresh the page
        find_person();
    });

});

and consider that you should split strings in this way in javascript:

var sample = 'first part'+
'second part'+
'third and last part';

semicolon is just for the last part.

Upvotes: -1

Pointy
Pointy

Reputation: 413826

Your initialization code for the HTML content you want to add is broken:

var title = 
"<div class=\"w3-container\">" +
"<h3>Find a person</h3>" + // <----- "+" instead of ";"
"</div>";

As it is, you're trying to append an incomplete block of HTML, so the browser just ignores it.

Upvotes: 1

lmilunovic
lmilunovic

Reputation: 191

Your "content_title" div is null when you are trying to access it.

There is high possibility that your document isn't fully loaded when you call your function on it.

Upvotes: 3

Related Questions