Parth Raghav Parth Raghav - 7 months ago 11
Javascript Question

get element's attribute or name using 'onload' function

How can I access element's attribute or name in 'onload' function ?

<script src="bla/bla/bla.js" data-name="blabla" onload="console.log(&quotloaded script with name ... &quot)"></script>


how can I reply "..." in above code snippet with the data-name attribute? I want to keep the code short and minimal?

Answer

Within the code contained in the text of the onload attribute, this refers to the element. So this.getAttribute("data-name") will give you the attribute value.

But I would steer you away from using onxyz attribute event handlers. Look into using modern techniques for hooking up events, not least because of the hassles of writing JavaScript code where HTML text is expected.

Comments