Jump to content

Why document.getElementsByClassName("timeformat")[0]; undefined?


pstein

Recommended Posts

At first have a look at a sample webpage (from a german news magazine):

https://www.spiegel.de/panorama/yellowstone-nationalpark-serie-von-bison-attacken-in-den-usa-a-7530e432-ba46-4e0d-a89e-2b2c07ccbbdd

As you can see there is a date and time just below the headline. And the "time" element has a class "timeformat"

Now when I execute the following javascript code from a *.user.js script

var pane = document.getElementsByClassName("timeformat")[0];
alert (pane);

Then the alert shows "undefined".

As a result I cannot assign something else like in

pane.innerHTML = "foobar";

Why does Firefox (on Windows) not find the <time> element with the class "timeformat"?

Link to comment
Share on other sites

Most likely your code is running before the page has finished loading which means the element hasn't been created yet. You have to wait until the document has finished loading, which can be done with the DOMContentLoaded event.

window.addEventListener("DOMContentLoaded", () => {
  var pane = document.getElementsByClassName("timeformat")[0];
  alert (pane);
});

 

  • Like 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...