How to check if an element is undefined?

I want to check if the specific attribute of the DOM element is undefined - how to do this?

I tried something like this:

if (marcamillion == undefined) {
    console.log("Marcamillion is an undefined variable.");
}
ReferenceError: marcamillion is not defined

As you can see, the reference error tells me that the variable is not defined, but my check ifobviously does not work, because it creates the js standard ReferenceError, unlike the error message that I get in mine console.log.

Change 1

Or even better, if I try to determine if the attribute of an undefined element is as follows:

$(this).attr('value')

What would be the best way to determine if it is undefined?

+5
source share
2 answers

Usage typeof:

if (typeof marcamillion == 'undefined') {
    console.log("Marcamillion is an undefined variable.");
}

Edit for second question:

if ($(this).attr('value')) {
    // code
}
else {
    console.log('nope.')
}
+8
source
if (typeof marcamillion === 'undefined') {
    console.log("Marcamillion is an undefined variable.");
}

, === == .

+4

All Articles