Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I target an element before it's closed?

I'm wanting to add a class to the body tag without waiting for the DOM to load, but I'm wanting to know if the following approach would be valid. I'm more concerned with validity than whether the browsers support it for now.

<body>
  $("body").addClass("active");
  ...
</body>

Thanks, Steve

like image 522
Steve Perks Avatar asked Nov 02 '25 13:11

Steve Perks


1 Answers

The .elementReady() plugin seems to be pretty close to what you're looking for.

It operates by using a setInterval loop, that exits as soon as document.getElementById() returns an element for a given id.

You could probably do a slight modification of that plugin (or commit an update/patch) to allow for generic selectors (at least for "tagNames") instead of just ids.

I don't believe there is any truly reliable cross-browser compatible way to address an element before it's loaded - other than this sort of setInterval hacking

Unless you are able to place your javascript command inside the target element like @JasonBunting suggests.

like image 119
Már Örlygsson Avatar answered Nov 05 '25 07:11

Már Örlygsson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!