'Iframe contentWindow getElementById Question

First, my iframe page is in same domain (in the same project of parent). I tried to get the element by id of the iframe. This is my /views/index.html

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri = "http://java.sun.com/jsp/jstl/functions" prefix = "fn" %>
<!DOCTYPE html>
<html>
<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
<title>SubWay</title>

</head>
<body>
    
    
    <iframe src="/test" id="test"></iframe>
    
    <script>
    console.log(document.getElementById("test").contentWindow.document.getElementById("test));
    </script>
    
    
</body>
</html>

This is my iframe, which is /views/test.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<div id="test">test</div>
</body>
</html>

So, simply, I tried to get the div from test.jsp in the index.jsp. iframe shows up in the index.jsp. However, as I tried to print console.log(document.getElementById("test").contentWindow.document.getElementById("test)); console shows null. Yet, "document.getElementById("test").contentWindow.document" this is not null;



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source