0

I created a .js file for the directory of html of files I am working with. The purpose of the .js file is to remove element ids. So in my .js file I currently have the script

var element=document.getElementById("id1");
element.parentElement.removeChild(element);

which works perfectly fine and does what I need to do. Now If I was to include an additional script to remove the id element of a different html page

var element = document.getElementById("id1");
element.parentElement.removeChild(element); 

var elem = document.getElementById("id2");
elem.parentElement.removeChild(elem);

Only the first script is executed and the second is not in addition I receive the message "Uncaught type error: cannot read 'parentElement' of null. I would think that each html page would read the .js file and match the corresponding element it is referring too and make the change.

JVDL
  • 1,157
  • 9
  • 16
NickJ
  • 25
  • 8

3 Answers3

0

Uncaught type error: cannot read 'parentElement' of null means that it could not find the element with the given id and therefore you can not try to find its parent element. If you wanted to make this more generic you could try abstracting it to a function

function removeElementById(elId) {
    var el = document.getElementById(elId);
    if (el) {
        el.parentNode.removeChild(el);
    }
}

Now whenever you try to remove an element it will first check that it is not "falsy" before attempting to remove the element from its parent.

JVDL
  • 1,157
  • 9
  • 16
0

It's like the error says, the parentElement of a non existing element is null, and null has no method 'removeChild' So you must check if element exists.

var element=document.getElementById("id1");
if(element) {
    element.parentElement.removeChild(element);
}
Michiel
  • 4,160
  • 3
  • 30
  • 42
0

The element (id2) you tried to find is probably not in DOM when the srcipt runs. You will need to check if it is null before accessing its methods.

Dragonmon
  • 114
  • 6