Get element responsible for the error

1

Is it possible to know which element in the HTML is responsible for the action causing the error in JavaScript?

code:

<button onclick="a(this);">GO!</button>
<script>
window.onerror = function(message, source, lineno, colno, error) {
  console.log(error.stack); // event.target = window
}
</script>

Output:

  

ReferenceError: a is not defined

     

at HTMLButtonElement.onclick (onerror.html: 1)

In this reference "HTMLButtonElement.onclick" says it's a button and it was in the onclick event, but at the same time it says nothing, I'm not able to select this element in any way, or in this way, using stack it's not possible? Would there be another way to "get" this element?

var domID = "HTMLButtonElement".id;
addObjLog(document.querySelector(domID)); //exemplo de uso
    
asked by anonymous 15.04.2016 / 21:27

1 answer

0

One way to do this is to catch the exception and re-launch it with an identifier of the element that caused the error.

<button id="btn" onclick="try{a(this);}catch(err){throw new Error(event.target.id)}">
    GO!
</button>
<script>
    window.onerror = function(message, source, lineno, colno, error) {
      console.log(error.message);
    }
</script>
    
15.04.2016 / 23:19