Question

As far as I know document.getElementById('myId') will only look for HTML elements that are already in the document. Let's say I've created a new element via JS, but that I haven't appended it yet to the document body, is there's a way I can access this element by its id like I would normally do 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 that? (I must tell that I don't want to store any reference to this particular element, that's why I need to access it via its Id)

Thank you!

Was it helpful?

Solution

If it isn't part of the document, then you can't grab it using document.getElementById. getElementById does a DOM lookup, so the element must be in the tree to be found. If you create a floating DOM element, it merely exists in memory, and isn't accessible from the DOM. It has to be added to the DOM to be visible.

If you need to reference the element later, simply pass the reference to another function--all objects in JavaScript are passed by reference, so working on that floating DOM element from within another function modifies the original, not a copy.

OTHER TIPS

getElementById is a method on the document object. It's not going to return anything not in the document.

On not storing a reference, huh? If you could magically pull it out of the air by id, then the air would be a reference to it.

If you've created it, just pass the object to other functions and access it directly?

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);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top