Home > Mobile >  Get width and height of an iframe with JavaScript
Get width and height of an iframe with JavaScript

Time:02-23

I have an iframe on a page. For this example, its height is 0px and width is 100px.

I want to console.log these values with JavaScript.

At the moment I can access the iframe using window.frames[0], but how do I then get the width and height? What I'm doing currently returns undefined.

Here is the code and Fiddle

https://jsfiddle.net/prvmwg5q/

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<title>Page Title</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" href="">
<style>
</style>
<script src=""></script>
<body>

<iframe data-search-id="mainline-top" style="height: 0px; width: 100px;">
Test
</iframe>

<script>

console.log(window.frames[0]);

console.log(window.frames[0].offsetHeight); // Undefined
console.log(window.frames[0].offsetWidth); // Undefined

</script>

</body>
</html>

CodePudding user response:

window.frames does not return the DOM element. https://developer.mozilla.org/en-US/docs/Web/API/Window/frames

Instead, give your iframe an id and use getElementById instead.

EDIT: Or, better, as @HereticMonkey points out:

document.querySelector('iframe')

  • Related