this.name returns undefined in javascript

drnessie picture drnessie · Apr 3, 2011 · Viewed 40.9k times · Source

I am trying to remotely create an onclick for each <div> (to save typing time).

Here is the window.onload() function:

  window.onload = function() {
    divel = document.getElementsByTagName('div');
    for (var el in divel) {
      divel[el].onmouseover = function() {
        this.style.textDecoration = "underline";
      };
      divel[el].onmouseout = function() {
        this.style.textDecoration = "none";
      };
      divel[el].onclick = function() {
        document.getElementById('game').src = "/games/" + this.name;
      };
    }
  }

The name of every <div> is "flyingsheep" - this value was set by <div name="flyingsheep">.

When I click the <div>, the iframe "game" takes me to the webpage "/games/undefined".

Answer

Farzin Zaker picture Farzin Zaker · Apr 3, 2011

This will work. the problem is corrected.

just use : this.attributes["name"].value

window.onload = function() { 
        divel = document.getElementsByTagName('div');
        for(var el in divel){
        window.alert(divel[el].name);
            divel[el].onmouseover = function(){ this.style.textDecoration = "underline"; };
            divel[el].onmouseout = function(){ this.style.textDecoration = "none"; };
            divel[el].onclick = function(){document.getElementById('game').src = this.attributes["name"].value;} 
        }
}