0

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.

Nyghtqore
  • 1
  • 5

2 Answers2

0

document.getElementById(this) will won't work,you can try with below

function getElementId(obj){
  console.log(obj.id)
}
<button id="test" onclick="getElementId(this);"> Test </button>
flyingfox
  • 13,414
  • 3
  • 24
  • 39
0

The this object inside your getElementId function is bound to the window object or undefined depending on the stric mode option.

Pass the clicked this to the getElementId function. And inside the function you can use the argument to get the Id of the button.

<button id="test" onclick="getElementId(this);"> Test </button>
<script>
    function getElementId(element){
        var x = element.getAttribute('id');
    }
</script>
Manuvo
  • 748
  • 5
  • 15