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:
What is wrong?
How can I debug this? How can I find out what this
refers to? I am using firebug.
Thanks a lot.
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
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With