Home > Software engineering >  access a dom element of a different page in Javascript
access a dom element of a different page in Javascript

Time:08-07

How do we access a DOM element of a different pages in javascript, let's say we have page1.html and page2.html and we would like to access an element of the page2.html once we click on a button on the page1.html. In vanilla Javascript.

CodePudding user response:

Usually in simple terms you have to pass data to the backend and the backend passes data.

In order to pass values from a page to another. If you have a back-end server, POST request can be used.

If you have no backend server to support, then your only way to do it is by using GET request or Local Cookies only.

You can also follow this link Change element attribute of another page and find some infomation here may you will gain more insights.

CodePudding user response:

I'm sure there are dozens of previous versions of this question with answers, but they're proving surprisingly hard to search for...

You can't, unless

  1. You have a reference to the other window containing the other page,

    and

  2. The two pages are from the same domain (or close enough).

So in the normal case, you can't do it, because you don't have either of those things.

There are several ways a window can get a reference to another window's document:

  • If page1.html opened page2.html via window.open, open returns a reference to the new window.
  • If page1.html contains page2.html as an iframe, it can get a reference to the window object for that iframe using the contentWindow property of the iframe element in page1.html. (Or, in this case, get the document directly via contentDocument — provided #2 above is satisified.)
  • If page1.html was opened by page2.html, it has access to page2.html's window via the opener global.
  • If page1.html is an iframe within page2.html, it has access to page2.html's window via the parent global.
  • If page2.html was opened such that the window it's in was given a name (for instance, window.open(someURL, "example")), a subsequent call to window.open("", "example") will return a reference to the existing window (at least if it's in the same origin; there may be restrictions).

Again, though, having a reference to the other window is only half the story (#1), #2 still applies.

  • Related