I want to create a function that gets the ID of the element clicked. For example the button
<button id="test" onclick="getElementId();"> Test </button>
I thought about using this to get the function running
<script>
function getElementId(){
var x = document.getElementById(this).getAttribute('id');
}
</script>
But the console keeps saying
"Uncaught TypeError: Cannot read properties of null (reading ‘getAttribute’)
at getElementId ((Index):83:48)
at HTMLButtonElement.onclick ((Index):80:52)"
I get, that this returns empty.
3
Answers
Maybeb try with a sql query if is in a database
try something like
SELECT * FROM ‘ID’
and then put it in a a javascript function
document.getElementById(this)
will won’t work,you can try with belowThe
this
object inside yourgetElementId
function is bound to thewindow
object or undefined depending on the stric mode option.Pass the clicked
this
to thegetElementId
function. And inside the function you can use the argument to get the Id of the button.