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.
Asked
Active
Viewed 542 times
-1
Ahmed Ashour
- 5,179
- 10
- 35
- 56
Tycoon Kabuzi
- 1
- 1
1 Answers
0
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
You have a reference to the other window containing the other page,
and
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.htmlopenedpage2.htmlviawindow.open,openreturns a reference to the new window. - If
page1.htmlcontainspage2.htmlas an iframe, it can get a reference to the window object for that iframe using thecontentWindowproperty of theiframeelement inpage1.html. (Or, in this case, get the document directly viacontentDocument— provided #2 above is satisified.) - If
page1.htmlwas opened bypage2.html, it has access topage2.html's window via theopenerglobal. - If
page1.htmlis an iframe withinpage2.html, it has access topage2.html's window via theparentglobal. - If
page2.htmlwas opened such that the window it's in was given a name (for instance,window.open(someURL, "example")), a subsequent call towindow.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.
T.J. Crowder
- 1,031,962
- 187
- 1,923
- 1,875
-
1Thank you so much. I'm going to get deep into that. – Tycoon Kabuzi Aug 06 '22 at 11:09