2

This fires the onload event:

<!DOCTYPE html>
<html>
<body onload="alert('Hello')">
<p> Demo </p>
</body>
</html>

This does not fire the onload event:

<!DOCTYPE html>
<html>
<body>
<p id="demo" onload="alert('Hello')"> Demo </p>
</body>
</html>

In the second example, why is the event not firing?

  • Because your `p` never gets _loaded_ it just gets read, parsed etc... Then when the `body` is loaded (parsing has finished etc...), the event gets fired. In short, only the `body` and its parents receive that event. – somethinghere Feb 02 '17 at 14:20

2 Answers2

8

The elements that support onload are

<body>, <frame>, <iframe>, <img>, <input type="image">, <link>, <script>, <style>

A way to access any other element on load could be by adding a script tag, like below, though it depends very much on what you want to achieve

    <!DOCTYPE html>
    <html>
    <body>
      <p id="demo"> Demo </p>
      <script>console.log( document.getElementById('demo').textContent );</script>
    </body>
    </html>
dippas
  • 58,591
  • 15
  • 114
  • 126
Asons
  • 84,923
  • 12
  • 110
  • 165
0

the onload property/event is only for the body, if you want to make some modifications to the <p> you should do it in a function defined in the body onload property

Nickydonna
  • 802
  • 1
  • 5
  • 18