Skip to content
Advertisement

this.name returns undefined in javascript

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".

Advertisement

Answer

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;} 
        }
}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement