0

I want to appendChild an element to another page after clicking a button.

I used document.getElementById() to select the element I want to appendChild to.

But it throws this error in the console - Cannot read properties of null (reading 'appendChild').

It works when I appendChild paragraph to the same page in which I click the button.

For both html documents I load the script at the bottom.

class Pojistovna {
     constructor(){
      this.tableOfInsured = document.getElementById("table-of-insured-container")
      
      this.createInsured() 

  }
    createInsured() {
      this.continueButton.addEventListener("click", () => {

       let paragraph = document.createElement("p")
       paragraph.textContent = "Hi"
       this.tableOfInsured.appendChild(paragraph)

    }
  }

}

  • Make sure that you have an element with this ID in this document (You can't just append an element to another page). – NNL993 Aug 10 '22 at 09:10
  • 1
    Nothing in your code attempts to work across windows. Your script being in both pages, just on its own, doesn't in any way *connect* those pages. You have to do something to connect them. `document.getElementById` or other such will only work *within the document you use them on*. To access an element in another window, you have to use methods on the other window's document. (You'll also have to use `createElement` on that other document.) The answers linked questions offer some insight into cross-window programming. – T.J. Crowder Aug 10 '22 at 09:11

1 Answers1

-2

Move this.tableOfInsured = document.getElementById("table-of-insured-container") to the top of createInsured fun.