W
W
weranda2018-01-28 17:36:01
JavaScript
weranda, 2018-01-28 17:36:01

Is it possible to place JS above HTML and then wait and apply to the DOM element that appears?

Greetings
Is there any function in JS that allows you to wait for a certain element on the page to load, and when it appears, execute a function? Let me explain. The structure of the document is something like this:

<head>
    <script>
        var myElement = document.querySelector('.two');
        myElement.setAttribute("style", "color: red;");
    </script>
</head>
<body>
    <p class="one">one</p>
    <p class="two">two</p>
    <p class="three">three</p>
</body>

We put JS in HEAD, it seems that it cannot be applied to p.two yet ...
Is there some kind of "function" that will allow you to wait for a specific p.two element and do something when it appears, but do it before loading the third element (p.three) and in that order - JS at the top, BODY at the bottom?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrey Tsvetkov, 2018-01-28
@yellow79

You can wait for the entire DOM, I would even say I recommend

document.addEventListener("DOMContentLoaded", function(){
  var myElement = document.querySelector('.two');
  myElement.setAttribute("style", "color: red;");
});

D
Denis Knyazev, 2018-01-28
@axaxa_man

there are several options here:
https://stackoverflow.com/questions/17071697/how-t...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question