Reputation: 51
I have a problem with getting the div's ID from my application. I have a JSP file, which generates a HTML. I want to fetch div ID, but every time my alert is that id name is undefined.
In my JS file there is a simple function:
function myFunction(){
alert(this.id);
}
Divs IDs are generated dynamically. In my JSP file I have a simple onclick connection.
What's the reason of not having an ID as a result of the click?
Upvotes: 0
Views: 73
Reputation: 68933
this
refer to Window
object which does not have property named id, thus you get undefined
. Pass this
to the function so that you can refer that inside the function:
Demo:
function myFunction(el){
//console.log(this.constructor.name); //Window
alert(el.id);
}
<div id="test" onclick="myFunction(this)">Test Container</div>
Upvotes: 2
Reputation: 537
this refers to the object being passed to the function.
<div id="test" onclick="myFunction(this)">Test Container</div>
<script>
function myFunction(arg){
alert(arg.id);
}
</script>
Upvotes: 0