Search code examples
javascriptjqueryhtmlreferencehtml-object

Reference object window's element ids with JS


I'm using a template.html file to house my header & menu bar and using JS to insert page content per individual index.html files. I house template.html in my root file and subfolders house an index.html (which pulls in the template.html as an object) and script.js.

I need the index.html file to load the script.js file while still having the script.js file apply to the template.html file, but cannot figure out how to have the JS reference inside the index.html object. I've seen something done like this before-ish for iframes, but could not get it to apply the same way for object elements.


Here's the shortened files:

template.html

<!-- header & menu html -->
<div>
  <div id="middleLeft"></div>
  <div id="middleRight"></div>
</div>

references/index.html

<object type="text/html" data="../template.html"></object>

references/script.js

jQuery(function ($) {

window.onload = function() {
  $('#middleRight').innerHTML = rightText;
  $('#middleLeft').innerHTML = leftText;
}

var leftText = "<p>left text</p>";
var rightText = "<p>right text</p>";

As is, the script.js only works if it's loaded within the template.html, but it needs to be loaded within the index.html. Is there a way to load it in index.html but still let it reference elements within the template.html object? Thanks for your help!


Solution

    • jQuery $() has no .innerHTML method, rather .html()
    • Assign an ID to your <object> so you can easily target it
    • You should wait for the <object> is loaded
    • You can access than the content using contentDocument

    Here's an example

    <object id="myObj" type="text/html" data="../template.html"></object>
    

    jQuery(function ($) {
    
        var leftText = "<p>left text</p>";
        var rightText = "<p>right text</p>";
    
        $("#myObj").on("load", function() {
    
            console.dir(this.contentDocument);                 // #document
            console.dir(this.contentDocument.documentElement); // html
    
            var $doc = $( this.contentDocument );
    
            $doc.find('#middleRight').html( rightText );
            $doc.find('#middleLeft').html( leftText );
    
        });
    
    });