Home javascript How to implement a pure JS analog of $ (document) .ready?

How to implement a pure JS analog of $ (document) .ready?

Author

Date

Category

Same thing only in JS. How to translate?

$ (document) .ready (function () {
    $ ("# form_error_message_frontend + div & gt; div: last-child label"). addClass ("last");
  })

Answer 1, authority 100%

Something like this:

document.addEventListener ('DOMContentLoaded', function () {// Analogue $ (document) .ready (function ( ) {
 // If one element should be found
 if ((e = document.querySelector ("# form_error_message_frontend + div & gt; div: last-child label"))! == null)
  e.classList.add ('last'); // Analogue of selection and class assignment
 // If there are many elements
 Array.prototype.forEach.call (document.querySelectorAll ("# form_error_message_frontend + div & gt; div: last-child label"), function (e) {
  e.classList.add ('last');
 });
});

Answer 2, authority 43%

there is a good answer here

90 +% browsers will cover this solution for waiting for the download to finish

document.addEventListener ("DOMContentLoaded", function (event) {
 // do work
});

for 95 +% browsers you can use querySelector / querySelectorAll

methods

var el = document.querySelector ("# form_error_message_frontend + div & gt; div: last-child label");
el.className + = el.className? 'last': 'last'

Answer 3, authority 7%

It may be enough for you to add deferred script loading with the “defer” attribute in & lt; script & gt;
This will allow the script to wait for the entire DOM tree to load and then launch.


Answer 4, authority 2%

& lt;! DOCTYPE html & gt;
& lt; html & gt;
& lt; head & gt;
& lt; meta charset = "UTF-8" & gt;
& lt; title & gt; Example & lt; / title & gt;
& lt; script language = "JavaScript" & gt;
function startFunction () {
alert ("Hi there!");
}
& lt; / script & gt;
& lt; / head & gt;
& lt; body onload = "startFunction ()" & gt;
& lt; / body & gt;
& lt; / html & gt; 

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions