DWigley DWigley - 4 months ago 14
Javascript Question

document.getElementById is returning null even after being created

I have some code that I'm trying to run to get an existing element however it keeps returning null despite it existing in the developer console. I've read some stuff about waiting until the window loads before making a call but the code where I am trying to put this does not run on startup and waits until a user action.

I have even run the following and it returns null:

massText = document.createElement('mass_div');
console.log(document.getElementById('mass_div'));


Can anyone tell me why this returns null? I just created the element so why can I not get it? I have even tried making it initially on start up and then getting it and it still returns null. I would love to be able to edit existing elements rather than keep creating them to just modify their display text which I do by:

massText.innerHTML = "blah";


Here is more context. It's not exactly like this:

//lots of functions that create a model and then call this update method. Called every 500ms

function updateText() {
massText = document.createElement('mass_div');
massText.style.position = 'absolute';
massText.style.width = 100;
massText.style.height = 100;
massText.style.backgroundColor = "green";
massText.innerHTML = "Mass of the star is " + matches[pos] + " Solar Masses";
massText.style.top = window.innerHeight / 10 + 'px';
massText.style.left = window.innerWidth / 50 + 'px';
document.body.appendChild(massText);
}


This creates a ton of copies of the element "mass_div"

I would like to append these by doing something like this however it says massText is null

function updateText() {
if (document.getElementById('mass_div') == null){
massText = document.createElement('mass_div');
}else {
massText=document.getElementById('mass_div');
}
massText.style.position = 'absolute';
massText.style.width = 100;
massText.style.height = 100;
massText.style.backgroundColor = "green";
massText.innerHTML = "Mass of the star is " + matches[pos] + " Solar Masses";
massText.style.top = window.innerHeight / 10 + 'px';
massText.style.left = window.innerWidth / 50 + 'px';
document.body.appendChild(massText);
}

Answer

For this to work you should do:

var massText = document.createElement('div');
massText.id='mass_div'
document.appendChild(massText)
console.log(document.getElementById('mass_div')); //This is working

In your code you have 2 issues:

  • The function createElement get element name not element id. So, you have to add the id later
  • The function getElementById get only elements that appended to document. So you have to add the element to the document before