Can I target an element before it's closed?

Question!

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



Answers

Rather than adding a class to your <body> tag you might find it easier to add a class to the <html> tag by doing:

<script type="text/javascript">
    document.documentElement.className = 'active';
</script>
By : Ian Oxley


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.



Basically, the answer is no. In IE6 and Firefox 2 (the browsers I have the most experience in), the element isn't in the DOM until after the close tag (or the page is done rendering, for invalid XHTML). I know that jQuery provides a convenience methods that seems to react quickly enough to avoid "flicker" in most cases. You would use it like so:

<script>
  $(document).ready(function() {
    $("body").addClass("active");
  });
</script>
<body>
  ..
  ..
  ..
</body>

But that's about it for javascript.

Of course, in the example you provided, you could easily just accomplish the same effect with:

<body class="active">
</body>
By : Adam Ness


This video can help you solving your question :)
By: admin