Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

this.getAttribute is not a function

Tags:

javascript

I am new to Javascript. I want to write a javascript code that when I click a button, the alert window pops up and writes data-message attribute. Here is my code:

<button type="button" data-message="a1" onclick="pop()">click</button>

<script>
  function pop() {
    alert(this.getAttribute("data-message"));
  }
</script>

but I get the error

TypeError: this.getAttribute is not a function
alert(this.getAttribute("data-message"));

I have two questions:

  1. What is wrong?

  2. How can I debug this? How can I find out what this refers to? I am using firebug.

Thanks a lot.

like image 749
user2725109 Avatar asked Nov 28 '22 07:11

user2725109


2 Answers

You need send this on the button like

<button type="button" data-message="a1" onclick="pop(this)">click</button>

and the Js, capture who is calling it.

function pop(e) {
    alert(e.getAttribute("data-message"));
  }

Working DEMO

like image 142
Wilfredo P Avatar answered Nov 30 '22 20:11

Wilfredo P


In your function, this is the window object, and it has no getAttribute method. You need to pass this as an argument from the onclick attribute:

<button type="button" data-message="a1" onclick="pop(this)">click</button>

<script>
  function pop(button) {
    alert(button.getAttribute("data-message"));
  }
</script>
like image 21
Barmar Avatar answered Nov 30 '22 21:11

Barmar