Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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

Solution 2:

Generally (irrespectively if it is java, javascript or c#) when dealing with XML or Html Dom the algorithm is the same and simple: 1. create or load document from string or similar, 2. if no root node (new document) create a root node or find an existing root node, 3. create child node with attibutes and values as you desire (there are multiple constructors), 4. append the child node to the root node (or another child - as you wish). 5. you may fire getElementById or GetElementByTag or similar to find node created in point 3.

You have pasted very little code but I assume that you have skipped step 4 and that is the reason of NRE.

In example the missing parts (should be placed before console.log("aaa"): Js:

var aaa = document.createElement("mass_div");
document.body.appendChild(aaa);

C#:

var aaa = doc.CreateElement("mass_div");
rootNode.AppendChild(aaa);

Java:

var aaa = doc.createElement("mass_div");
doc.appendChild(aaa)

More or less this should suit your needs and hope it helps. Kind regards,

P.Sz.

Solution 3:

Here we go:

var massText = document.createElement('input');  //Here is you create the element input.
masstext.id ='mass_div';      //Here is you set id for created element inputdocument.appendChild(massText);  //Added to main documentconsole.log(document.getElementById('mass_div'));  //handle your element by id and log

This is working 100% !

Post a Comment for "Document.getelementbyid Is Returning Null Even After Being Created"