-3

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>
Sumit patel
  • 3,807
  • 9
  • 34
  • 61
Herman Tam
  • 75
  • 1
  • 1
  • 5
  • *"I thought browser only executed the code once"* Like if they were producing a single png shot of the page ? No that's not what they do. At every modification of the DOM, they do reflow and repaint every elements. – Kaiido Mar 21 '17 at 06:05
  • If so, why would the js generated html turn red instead but not green? – Herman Tam Mar 21 '17 at 06:50
  • because your first `h2` doesn't match `:first-child` pseudo selector. ` – Kaiido Mar 21 '17 at 06:53

1 Answers1

0

When a HTML page is loaded, CSS rules are defined during parsing of the page. So, even when you add a new element to DOM, these CSS rules hold good.

That's why 'hi' turns to red and 'hii' turns to yellow.

Checkout this answer

Community
  • 1
  • 1
Yogesh
  • 699
  • 1
  • 6
  • 21