Skip to content
Advertisement

Manipulate multiples HTML files with javascript

Is it possible to manipulate more than one HTML file in the same script? For example, i have a <div id="div1"> on my index.html, and <div id="div2"> in another HTML file inside of another folder.

What i trying to do is get the content of the second div and replace to my “div1”, but the “traditional way” doesnt work:

function replaceDiv(){
    let div1 = document.querySelector('#div1')
    let div2 = document.querySelector('#div2')
    div1.innerHTML = div2
}

I’m new to programming, sorry if this is a dumb/obvious question haha

ps: both files have the link for the same script.

psĀ²: i know that i can manually write the string with innerHTML, but i wanna know if it’s possible to do this

Advertisement

Answer

Why this doesn’t work

The document object in JavaScript is representative of the currently rendered page’s content, it can only exist when the page that loads this script is actively being rendered.

A web browser can only render one HTML file at a time (e.g. either index.html or other.html). Say #div1 is in index.html and #div2 is in other.html; the script can only see that one of these div elements exists since the document is scoped to the current page.

This is the same reason that you can reuse ids across multiple HTML files on the same website with no unexpected behavior.

Alternate Solution

Store this data (InnerHTML/the snippet needs to be shared) in the script itself since that can be requested on each page individually.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement