---
title: "原生js获取iframe中dom元素--父子页面相互获取对方dom元素"
author: "piperzero"
date: "2012-11-27T17:55:00Z"
tags: []
slug: "js-iframe-dom-dom"
draft: false
lastmod: "2013-01-07T09:55:02Z"
id: 1764478
url: "https://piperzero.iteye.com/blog/1764478"
---

用原生js在父页面获取iframe子页面的元素，以及在子页面获取父页面元素，这是平时经常会用到的方法，这里写一个例子来总结下：

1、父页面（demo.html），在父页面修改子页面div的背景色为灰色，原来为红色：

```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<title>demo主页面</title>
	<script type="text/javascript">
	window.onload = function(){
		var _iframe = document.getElementById('iframeId').contentWindow;
		var _div =_iframe.document.getElementById('objId');
		_div.style.backgroundColor = '#ccc';
	}
	
	</script>
</head>

<body>

<div id='parDiv'>父页面</div>
<iframe src="demo-iframe.html" id="iframeId" height="150" width="150"></iframe>  
</body>
</html>
```

2、子页面（demo-iframe.html），在子页面修改父页面div的字体颜色为红色，原来为黑色：

```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<title>子页面demo13-iframe.html</title>
	<script type="text/javascript">
	window.onload = function(){
		var _iframe = window.parent;
		var _div =_iframe.document.getElementById('parDiv');
		_div.style.color = 'red';
	}
	</script>
</head>

<body>
	<div id='objId' style='width:100px;height:100px;background-color:red;'>子页面</div>
</body>
</html>
```

3、效果图：

（1）没有加入js时的效果图：

![](http://img.my.csdn.net/uploads/201211/27/1354010206_9871.png)

（2）加入js后的效果图：

![](http://img.my.csdn.net/uploads/201211/27/1354010214_7036.png)