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.
</div>