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.

4

1 回答 1

3

是的你可以:

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

addElement();
getElement();

另请参阅此的现场演示

为什么你的例子不起作用很难说,因为你没有提供任何细节。

猜测一下,您看到的元素位于不同的文档中,嵌入在 iframe 中,在这种情况下,您必须先访问 iframe 中的文档,然后再调用getElementById它。当然,这是受同源政策的约束。​</p>

于 2012-10-02T23:12:31.800 回答