How to access the <img /> in document from iframe?

Member

by dana , in category: HTML & CSS , 18 days ago

How to access the <img /> in document from iframe?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by edmond_brakus , 13 days ago

@dana 

To access the in the parent document from an iframe, you can use the parent property in JavaScript. Here's an example code snippet:


In the parent document:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
<!DOCTYPE html>
<html>
<head>
  <title>Parent Document</title>
</head>
<body>
  <iframe src="child.html"></iframe>
  <img id="image" src="image.jpg" alt="Image">
</body>
</html>


In the child document (child.html):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
<!DOCTYPE html>
<html>
<head>
  <title>Child Document</title>
</head>
<body>
  <script>
    // Access the img element in the parent document
    var imgElement = parent.document.getElementById("image");
    console.log(imgElement);
  </script>
</body>
</html>


In this example, the child document has a script that uses the parent property to access the img element with the id "image" in the parent document. You can then perform any manipulations or operations on the element as needed.