1

I can see a DOM element with an ID of Foo by using the debug inspector.

This DOM element is inserted dynamically by a script that I do not have access to.

Because of this you can not see it when you do View->Source.

When I try to access the element using

document.getElementById('Foo'), it returns a null b.c. it can not find it.

Verified this in the debug console as well.

Is it possible to get elements that are inserted dynamically?

I ask b.c. I would like to remove the node.

1 Answers1

3

Yes, you can:

function addElement() {
    var foo = document.createElement('p');
    foo.id = "bar";
    document.body.appendChild(foo);
}
function getElement() {
    alert(document.getElementById('bar'));
}    

addElement();
getElement();

See also a live demo of this.

Why your example doesn't work is hard to say as you haven't provided any details.

At a guess, the element you are seeing is in a different document, embedded in an iframe, in which case you would have to access the document in the iframe before calling getElementById on it. This is, of course, subject to the same origin policy. ​

Community
  • 1
  • 1
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • As I suggested was likely, it is in a different document in an iframe. That iframe is on a different origin, so you can't (and since the advert is the "payment" they take for providing the service, you shouldn't even if you could). – Quentin Oct 02 '12 at 23:15
  • Most DOM inspectors will show nested documents in iframes as part of the DOM. They are still different documents. – Quentin Oct 02 '12 at 23:16
  • I looked at it in a DOM inspector. https://skitch.com/dorward/esqap/nested-document – Quentin Oct 02 '12 at 23:18
  • I guess everything in that iFrame is read only and protected by the Browser? –  Oct 02 '12 at 23:21
  • As I said in the answer, it is protected by the same origin policy. So most of it is inaccessible (not read only, completely inaccessible). A few parts will be write only. (Those parts do not include any of the element nodes as they all descend form things that cannot be read). – Quentin Oct 02 '12 at 23:23
  • that is neat...it's like they own part of the web application. –  Oct 02 '12 at 23:27
  • You have a script element with the src pointing to a URL on their server in your page. They *do* own part of the web application. – Quentin Oct 02 '12 at 23:34