I have problem understanding the behavior of this. In fact, I don't understand which DOM (document object model) does css follow to apply styling if javascript is applied to generate html. The behavior is expected before adding javascript for the code above. However, when javascript is added, this has strange behaviors that 'hi' turns to red and 'hii' turns to yellow. In fact, I don't understand why CSS could even apply styling to javascript generated html 'hi' because css stylesheet is applied before the function d() is executed in the body. Why would 'hi' turn red and 'hii' turn yellow? I thought browser only executed the code once from top to bottom. Could anyone please explain this? Thank you very much.
h2:first-child {
color: green;
}
h2:nth-child(2) {
color: red;
}
h2:nth-child(3) {
color: yellow;
}
<script type="text/javascript">
d();
function d() {
document.write("<h2>hi</h2>");
}
</script>
<h2>hii</h2>
<h2>hiii</h2>
<h2>hiiii</h2>