Yansky
Yansky

Reputation: 4760

DOM traversal up to window?

With the following bit of code -

var myEl = document.getElementById('myElement');
myEl.ownerDocument.defaultView;

does getting to the original window via ownerDocument.defaultView mean that I'm traversing up the DOM from the myEl element to the document and then to the window?

Upvotes: 1

Views: 292

Answers (3)

anthony sottile
anthony sottile

Reputation: 70243

I think traversal would be like:

var theParentNode = document.getElementById('myElement');

while(theParentNode = theParentNode.parentNode) {
    // do something
}

Upvotes: 0

mrk
mrk

Reputation: 5127

I wouldn't say this is traversing the DOM..more like shortcutting the DOM tree and going straight to the window.

Traversal could be something more like this:

var myEl = document.getElementById('#myElement');
while(myEl.parentNode)
{
    console.log("parentNode = " + myEl.parentNode);
    myEl = myEl.parentNode;
}
console.log("root parentNode = " + myEl);

Upvotes: 0

lonesomeday
lonesomeday

Reputation: 238115

It's not really traversing, per se.

Every DOM object has an ownerDocument property. This is the document that the node is associated with, if any.

Every document object has a defaultView property (provided your browser supports it -- not true in IE <9). This is the window object where the document is shown, if any,.

So it's really just reading a couple of properties from objects, rather than traversal.

Upvotes: 2

Related Questions