Max Cha
Max Cha

Reputation: 31

Can't acces to the height of a div in an Iframe

here is my problem: the size of my iFrame must vary according to the size of a div in it and when I try to get the size of this div everything I try returns 0

var childiFrame = document.getElementById("myDiv");
                        console.log(childiFrame,"here is my iframe");
                        var innerDoc = childiFrame.contentWindow.document; 
                        console.log(innerDoc,"here is the innerDoc where i have to find my div");
                        mdDiv =innerDoc.getElementById("md");
                        console.log(mdDiv,"here is my div !");// and i can see the clientHeight =245
                        var divHeight = mdDiv.clientHeight; // or offsetHeight or scrollHeight
                        console.log(divHeight,"the div height always equals 0 !");

I haven't seen anyone talk about this problem, so if anyone has any ideas, I'll take it!

Upvotes: 1

Views: 49

Answers (2)

Avdhesh Solanki
Avdhesh Solanki

Reputation: 144

Please put this script in the parent page -

<script>	
window.addEventListener('message', function(e) {
	var data = e.data.split('-'),
		scroll_height = data[0],
		iframe_id = data[1];
	if(iframe_id == 'iframe1')
		document.getElementById('iframe-container-1').style.height = scroll_height + 'px'; } , false);
</script>

Put this script in iframe

<script>
        setInterval(function () {
        window.top.postMessage(document.body.scrollHeight + '-' + 'iframe1', "*");
        }, 500);
</script>

Upvotes: 2

palaѕн
palaѕн

Reputation: 73886

I think you need to wait for iframe to fully load first using the onload event, then try to access the mdDiv attributes like:

var childiFrame = document.getElementById("myDiv");
console.log(childiFrame, "here is my iframe");
childiFrame.onload = function() {
  console.log('my iframe is loaded');

  var innerDoc = childiFrame.contentDocument ? childiFrame.contentDocument : childiFrame.contentWindow.document;
  console.log(innerDoc, "here is the innerDoc where i have to find my div");

  mdDiv = innerDoc.getElementById("md");
  console.log(mdDiv, "here is my div !");

  var divHeight = mdDiv.clientHeight; // or offsetHeight or scrollHeight
  console.log(divHeight);
};

Upvotes: 1

Related Questions