Questions & Answers

Prevent errors when array? variable is null

I'm trying to check against whether a div ID exists, and if its aria-label contains a specific string, so I can take other action. This seems straightforward, but I get errors when the div isn't on the page.

The error (in Codepen): Uncaught TypeError: Cannot read properties of null (reading 'attributes')

I thought I could solve the problem with an if statement, to see if the div exists before setting the by simply checking if the div ID exists first, but I'm still getting the error.

var test = document.getElementById('success_message’);

if (test) { 
  var successMsg = test.attributes;
  // the successMsg var is what fails me.

if (successMsg['aria-label'].value == "Lorem ipsum”)  {
    // do stuff A
  } else {
   // do stuff B


For reference, in HTML, the div looks like this, when it does exist on page:

<div id="success_message" aria-label="Lorem ipsum">
  Lorem ipsum etc. etc.
2023-01-17 00:47:00
successMsg will be undefined if the first if isn't entered into, so the second if will throw because you can't access properties of undefined. Either check to see that it exists before proceeding in the second, or (better) just put it all into one block.
Answers(0) :