Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I solve this "Cannot read property 'appendChild' of null" error?

I tried to use this code below, which adds buttons in slideshow on my site:

window.onload = function loadContIcons() {
    var elem = document.createElement("img");
    elem.src = "http://arno.agnian.com/sites/all/themes/agnian/images/up.png";
    elem.setAttribute("class", "up_icon");

    var id = "views_slideshow_controls_text_next_slideshow-block";
    if (id !== 0) {
        document.getElementById(id).appendChild(elem);
    } else console.log("aaaaa");

    var elem1 = document.createElement("img");
    elem1.src = "http://arno.agnian.com/sites/all/themes/agnian/images/down.png";
    elem1.setAttribute("class", "down_icon");

    var id1 = "views_slideshow_controls_text_previous_slideshow-block";
    if (id1 !== 0) {
        document.getElementById(id1).appendChild(elem1);
    } else console.log("aaaaa");
}

On the front page, where I have slideshow everything works good, but on the other pages the error Cannot read property 'appendChild' of null occurs.

like image 241
Arno Avatar asked Jul 30 '14 13:07

Arno


People also ask

How do I fix appendChild is not a function?

To solve the "appendChild is not a function" error, make sure to only call the appendChild method on valid DOM elements and place the JS script tag at the bottom of the body, after the DOM elements have been declared. Copied! const boxes = document.

What does it mean Cannot read property of null?

The "Cannot read property 'value' of null" error occurs when: trying to access the value property on a null value, e.g. after calling getElementById with an invalid identifier. inserting the JS script tag before the DOM elements have been declared.

What does appendChild mean in JavaScript?

The appendChild() is a method of the Node interface. The appendChild() method allows you to add a node to the end of the list of child nodes of a specified parent node.


1 Answers

The element hasn't been appended yet, therefore it is equal to null. The Id will never = 0. When you call getElementById(id), it is null since it is not a part of the dom yet unless your static id is already on the DOM. Do a call through the console to see what it returns.

like image 164
eg_dac Avatar answered Sep 19 '22 14:09

eg_dac