0

This works

<body onload="document.body.classList.add('loaded'); document.body.removeAttribute('onload')">

and it's not a problem for this particular case, but I need the same fuctionality on multiple elements and I hope there's a solution without giving all of them an id attribute.

I tried

<body onload="this.classList.add('loaded'); this.removeAttribute('onload')">

and

<body onload="self.classList.add('loaded'); self.removeAttribute('onload')">

but (obviously to some) it doesn't work.

How do I get the element in which JavaScript is called from attributes like onload, onclick, etc.?

Elaborating my use-case: All of my styles, except critical.css are loading with a non-blocking hack like

<link rel="stylesheet" media="none" onload="if(media!='all')media='all'" href="//fonts.googleapis.com/css?family=Open+Sans:300,400,600,700%7CPT+Sans+Narrow%7CSource+Sans+Pro:200,300,400,600,700,900&amp;subset=all&amp;display=swap" type="text/css">

I don't like that the onload="if(media!='all')media='all'" part is still visible in DevTools after everything is loaded properly. I also don't completely understand how to do this in a better way. It would be interesting to find out the answer to my exact question, but I would also much appreciate an answer that offers the best approach. My stack is HTML5, CSS, vanilla JavaScript, PHP 7.2. No frameworks at the moment (not counting Bootstrap).

s3c
  • 558
  • 7
  • 17
  • Does this answer your question? [Difference between this and self in JavaScript](https://stackoverflow.com/questions/16875767/difference-between-this-and-self-in-javascript) – Mister Jojo Jul 09 '20 at 11:51
  • better to use DOMContentLoaded event https://developer.mozilla.org/en-US/docs/Web/API/Window/DOMContentLoaded_event – Mister Jojo Jul 09 '20 at 11:53
  • @MisterJojo Elaborated a bit. See question. I don't exactly see how to use `DOMContentLoaded` and difference between `this` and `self` isn't too helpful since neither of them work. – s3c Jul 09 '20 at 13:00
  • I just think you have to do do all this JS code in a script part, not in head or body part – Mister Jojo Jul 09 '20 at 13:09

0 Answers0