1

I have got created a rather complex HTMLElement and would like to know id there is a way to run a getElementById on it before the element gets appended to the DOM.

What I have tried is to call the function like this:document.getElementById.call(newElement, "id");

and like this: Document.prototype.getElementById.call(newElement, "id");

in both cases the I just get the error Uncaught TypeError: Illegal invocation

Is there a posibility to do that or is it just not possible?

Note: I am trying to solve a JS problem here, thats why I do not want jQuery solutions.

Friedrich
  • 2,211
  • 20
  • 42

1 Answers1

2

You can do

var yourElement = newElement.querySelector('#someId');

Complete example :

var newElement = document.createElement('div');
newElement.innerHTML="<div id=a>AA</div><span id=b>BB</span>";
console.log(newElement.querySelector('#b').innerHTML) // logs BB

Note : IE7 isn't supported

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • +1 the only other option seems to be [creating another document](http://stackoverflow.com/questions/8227612/how-to-create-document-objects-with-javascript) and appending the element into it - that will give you a `getElementById` method. – kapa May 14 '14 at 14:00