pikkuu
pikkuu

Reputation: 71

Javascript getElementById in iframe

401 is the value I want to get in iframe..

<iframe id="meal" src="about:blank" name="re">
     <td id="calories3">401</td>      
</iframe>

Then I have this in .js file

    var iframe = document.getElementById('meal');
    var frameDoc = iframe.contentDocument || iframe.contentWindow.document;
    var test = frameDoc.getElementById('calories3');
    window.alert(test.value);

But it says "test" is undefined..

when i did typeof(test) in console it says "object"..

I don't know why my test is the whole "<td id="calories3">401</td> "

How can I get the number?

Upvotes: 0

Views: 303

Answers (3)

Karmacon
Karmacon

Reputation: 3190

I don't think you can directly stick a child node inside an iframe tag like that. You need to actually load the content into the iframe.

If you run console.log(iframe.childNodes); you'll see that it actually returns a text object instead of a td element. If you run console.log(test); it prints out null in the console, and typeof null == object.

Upvotes: 0

Yuran Liu
Yuran Liu

Reputation: 1

Is the iframe content was under the same domain as your page? If the iframe content was from outside of your domain, you cannot access it.

Upvotes: 0

Bryan Corey
Bryan Corey

Reputation: 760

You will need to access the innerHTML of the node, rather than the node itself. Try window.alert(test.innerHTML).

See Element.innerHTML

Upvotes: 2

Related Questions