skip to Main Content

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


  1. 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

    Login or Signup to reply.
  2. 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>
    Login or Signup to reply.
  3. 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>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search