Search code examples
javascriptglobalgetelementsbytagname

JavaScript - Maintaining Global Reference to Element Found Using getElementsByTagName


Let's say I wanted to find the last div on the page and do so using getElementsByTagName as below:

var divs = document.getElementsByTagName('div');
var div = divs[divs-1];

This all works fine, unless I want to access said div inside a function:

function a() {
 alert(div);
}

This results in an alert saying 'undefined'. However, if I know the ID of the div and find it using getElementById instead, the above function works as I would expect.

jsFiddle to illustrate what I mean.

Can anyone tell me how I can maintain a global reference to an element when using getElementsByTagName?


Solution

  • You have missed .length within []. Try:

    var div = divs[divs.length-1];
                         //^-----------------total amount of divs
    

    instead of:

    var div = divs[divs-1];