1

When selecting an ID or ClassName in Javascript it does not work. The class or ID does exist and is spelled correctly. Why does Javascript tell me that Undefined is not an object(evaluating 'header.style.height = ""') while the object is defined properly? The script below is just a plain example, but I can't select (almost) anything. No matter what ID or class I select. I know that it says it can't find the object, but why?

  var header = document.getElementById("header");
  window.onscroll = function() {scrollFunction()};
  function scrollFunction() {
    if (document.body.scrollTop > 128 || document.documentElement.scrollTop > 128) {
      header.style.height = "48px";
    } else {
      header.style.height = "";
    }
  }
Al John
  • 612
  • 5
  • 24
  • 1
    Try adding a `defer` attribute to script tag. Cause this script might be running before the DOM content is loaded. https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-defer – Saihaj Aug 26 '21 at 19:38
  • Put the variable declaration inside `scrollFunction` – Barmar Aug 26 '21 at 19:42
  • I went to your website and couldn't find `window.onscroll` in the JS. Which file is it in? – Barmar Aug 26 '21 at 19:44
  • @Barmar I had removed the script but it's on the site now. – Al John Aug 26 '21 at 19:48
  • 1
    The script using `getElementsByClassName`, not `getElementById`. Since that returns a list, you have to index it. `var header = document.getElementsByClassName("header")[0];` – Barmar Aug 26 '21 at 19:51
  • Or use `var header = document.querySelector(".header");` – Barmar Aug 26 '21 at 19:51
  • There's no `id="header"` anywhere in the document, why would you expect that to work? – Barmar Aug 26 '21 at 19:51
  • @Barmar Ahh, indexing it worked! Thanks a million :) – Al John Aug 26 '21 at 19:53

1 Answers1

0

you can try to maybe change var header = document.getElementById("header") to var header = document.getElementsByClassName("header")[0] because i saw in your website that there is a div with a class name of "header" and you need to add the [0] to select the first element of the node list returned from getElementsByClassName.

Hakim art
  • 9
  • 2
  • 1
    You need to index it, since `getElementsByClassName` returns a `NodeList`. – Barmar Aug 26 '21 at 19:46
  • @Barmar I've tried both giving the header an ID and using it, and its existing ClassName. Both give me the same Undefined message. – Al John Aug 26 '21 at 19:50
  • Make sure your script is at the end of the HTML, or in `$(document).ready()` – Barmar Aug 26 '21 at 20:02