Use getElementById for elements that have not yet been [DOM] in the DOM?

As far as I know document.getElementById ('myId') will only look for HTML elements that are already in the document. Let's say I created a new element through JS, but I have not added it to the document body yet, is there a way to access this element by its identifier, as usual, with getElementById?

var newElement = document.createElement('div');
newElement.id = 'myId';
// Without doing: document.body.appendChild(newElement);
var elmt = document.getElementById('myId'); // won't work

Is there a workaround for this? (I have to say that I do not want to store links to this particular element, so I need to access it through its identifier)

Thanks!

+5
source share
3 answers

, document.getElementById. getElementById DOM, . DOM, DOM. DOM, .

, - JavaScript , DOM , .

+5

getElementById - . .

, ? id, .

0

, ?

function createDiv()
{
  var newElement = document.createElement('div');
  doWorkWithDiv(newElement);
}

function doWorkWithDiv(element)
{
  element.className = 'newElementCSS';
  element.innerHTML = 'Text inside newElement';
  addToDoc(element);
}

function addToDoc(element)
{
  document.body.appendChild(element);
}
0

All Articles