0

Saw this error on the console - VM2134:1 Uncaught TypeError: Cannot read property 'children' of null

I think this is where it happened -

if (document.getElementById('confirmMsg').children.length > 0) {
    document.getElementById('confirm').classList.add('ui-state-error')
} 
else {
    document.getElementById('confirm').classList.remove('ui-state-error')
}

I'm not familiar with javascript but I feel like I need to make sure that element exists && has children? Please help fix this issue. Thank you!

1 Answers1

0

Did you put this code before or after the actual HTML? Because this could generate an error if the element isn't yet loaded.

A more obvious answer would be "heh, there's no such ID in the DOM" :)

And finally, you could do a test in order not to get this error...

Something along those lines:

function foo() {
    if (document.getElementById('confirmMsg')) {
        if (document.getElementById('confirmMsg').children.length > 0) {
            document.getElementById('confirm').classList.add('ui-state-error')
        } else {
            document.getElementById('confirm').classList.remove('ui-state-error')
        }
    } else setTimeout(foo, 1000);
}

Would call itself until the element exists, and then do the expected stuff.

I know there must be a cleaner and prettier way to do this, I was just trying to get the idea down :)