Skip to content

Javascript: Can I Use JS to Copy an HTML Element From One Page to Another?

New to JS. Couldn’t find any good solutions for this after researching, and seems like it shouldn’t be too complicated.

Say I have a page called page1.html with this code:

<div class="page1">
  <div class="wrapper">
    <p>Some text.</p>

Now, I have a second page, page2.html, with this code:

<div class="page2">

I want to make a copy of the div with class wrapper from page1.html, and insert it into page2.html, within the div with class page2.

Both pages share the same script.js file.

I tried something like this:

page1content = document.querySelector('.wrapper');
page2content = document.querySelector('.page2');

However, I’m getting errors on page1.html because the js can’t find the div with class page2, and I’m getting errors on page2.html because the js can’t find the div with class wrapper.

I found a similar question here, and a couple comments suggest using localStorage.

I am unfamiliar with localStorage so I tried to do some research, and tried something like this:

On page1.html I inserted this script at the bottom:

  var pageContent = document.querySelector(".page1").innerHTML; 
  sessionStorage.setItem("page1content", pageContent);

On page2.html I inserted this script at the bottom:


It didn’t work for me, but perhaps I used it incorrectly.

I also tried to use cloneNode(), but again, wasn’t sure how to transplant the clone of the element onto a new page, only onto the same page I’m cloning from.

Is there another way to accomplish what I’m trying to do?

Obviously this is a very basic example; my actual code will be pumping in much more content from page 1 to page 2, but I just want to get the concept working at least.



The code I had in my example in the description was almost correct, I just had to change sessionStorage to localStorage and it worked.

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