0

If width of the device visiting my site is <320 I want a <h3> to be removed. This is what I've tried with:

HTML:

<head>
    <script type="text/javascript" src="javascript.js"></script>
</head>
<body>
    <h3 id="title">Title</h3>
</body>

JavaScript:

if (document.documentElement.clientWidth <= 320) {

    document.write("Testing");

    var h3 = document.getElementById("title");

    h3.parentNode.removeChild(h3);
}

The "testing" label is printed on the screen but the <h3>is still there. What's wrong?

Wilhelm Michaelsen
  • 665
  • 13
  • 30

1 Answers1

3

At the time the script is executed, the h3 element has not been parsed, so it doesn't exist in the DOM.

Move the part of the script that removes it to after the h3 in the HTML.

Better yet, forget about using JavaScript and use media queries with h3 { display: none; } instead.

Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205