Parth Raghav Parth Raghav - 2 years ago 66
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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download