简体   繁体   中英

getAttribute Returns [object Window] Instead of Value

I am writing out a hierarchical set of elements to the DOM document using JavaScript and am debugging using FireBug on FireFox 20.0. Based upon what I see when examining the DOM using FireBug, it seems that the writing out is going fine. The part of interest has the following structure.

childNodes NodeList[ulcorner, lrcorner]
- 0 ulcorner    
    accessKey  ""
    accessKeyLabel""
    - attributes    [xcoord="134", ycoord="49"]
    + 0 xcoord="134"
    + 1 ycoord="49"

However, when I call

var ulCorner=upperElement.getElementsByTagName("ulCorner")[0];
top=ulCorner.getAttribute("yCoord");
left=ulCorner.getAttribute("xCoord");
console.log('top=' + top + ', left=' + left);

I get

top=[object Window], left=134

Why is top set to [object Window] instead of 49?

top is an existing property on the window object and it's non-writable https://developer.mozilla.org/fr/docs/DOM/window.top

var ulCorner=upperElement.getElementsByTagName("ulCorner")[0];
var top=ulCorner.getAttribute("yCoord");
var left=ulCorner.getAttribute("xCoord");
console.log('top=' + top + ', left=' + left);

The above should work, however it's not recommended to shadow existing global variables and I strongly advise you to select another variable name, unless your code doesn't run in the global scope.

 top=ulCorner.getAttribute("yCoord"); 

You are creating an implicitly (and accidently) global variable here, ie a property of the global object. The global object is window in browsers, and window.top is a non-writable " reference to the topmost window in the window hierarchy ". So your assignment has no effect, and it just returns the top window (whose stringification is "[object Window]" ).

To fix this, just add the var keyword :

var ulCorner=upperElement.getElementsByTagName("ulCorner")[0];
var top=ulCorner.getAttribute("yCoord");
var left=ulCorner.getAttribute("xCoord");

or use a multiple var-statement:

var ulCorner=upperElement.getElementsByTagName("ulCorner")[0],
    top=ulCorner.getAttribute("yCoord"),
    left=ulCorner.getAttribute("xCoord");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM