Get reference of window object from a dom element

JavascriptJquery

Javascript Problem Overview


I have a javascript code like this

var element = $("elementId");

I got the reference to the element (which is a div).

Now I need to get the reference to the window in which this div element resides. But the problem is, here the $ is passed from a different window. So now the element resides in a different window.

How to get reference to that window object which contains this div element? Pls Help.

Javascript Solutions


Solution 1 - Javascript

Get a reference to the DOM node, use the ownerDocument property to get a reference to the document, then read its defaultView property (parentWindow for IE8-) to get a reference to the window:

var $element = $('#elementId');
var element = $element[0];
// Assume that element exists, otherwise an error will be thrown at the next line
var doc = element.ownerDocument;
var win = doc.defaultView || doc.parentWindow;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAniketView Question on Stackoverflow
Solution 1 - JavascriptRob WView Answer on Stackoverflow