Manish Sharma Manish Sharma - 1 year ago 53
Javascript Question

div innerhtml object access parent html div

I have a main.html containing the following div:

<div id="main">

I want to dynamically load html in this div (say page1.html and page2.html). I am able to accomplish this through the following code :

document.getElementById("main").innerHTML='<object type="text/html" data="page1.html" ></object>';

Now, I want to have a button id="btn1" in my page1.html, which should load page2.html into div "main" of my parent main.html.
However, in page1.html, I am not able to locate my container div "main"

document.getElementById("main") // returns null

Thanks in advance for the help!


Your issue is trying to use a single page's DOM to interact with content loaded in through an iframe or object. Using these makes life very difficult for a JavaScript developer.

If you are using only plain JavaScript, I would suggest you instead use an AJAX request to load in HTML directly through the DOM instead of transcluding this content using old methods.

Here's a beginner's guide to plain-JS AJAX. Frameworks like jQuery simplify the process immensely.

Otherwise, no. You cannot access that node's content because of Cross-Site Scripting security features.