Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if an element is undefined? [duplicate]

Tags:

javascript

I would like to check to see if a particular attribute of a DOM element is undefined - how do I do that?

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 is telling me that the variable is not defined, but my if check is clearly not working, because it is producing the standard js ReferenceError as opposed to the error message I am looking for in my console.log.

Edit 1

Or better yet, if I am trying to determine if the attribute of an element is undefined like this:

$(this).attr('value')

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

like image 279
marcamillion Avatar asked Mar 26 '13 09:03

marcamillion


2 Answers

Using typeof:

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

Edit for the second question:

if ($(this).attr('value')) {
    // code
}
else {
    console.log('nope.')
}
like image 184
romainberger Avatar answered Oct 24 '22 17:10

romainberger


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

Note that using === instead of == is considered better style.

like image 7
Fabien Avatar answered Oct 24 '22 16:10

Fabien