16

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?

marcamillion
  • 32,933
  • 55
  • 189
  • 380
  • 1
    possible duplicate of [How to determine if variable is 'undefined' or 'null'](http://stackoverflow.com/questions/2647867/how-to-determine-if-variable-is-undefined-or-null) and http://stackoverflow.com/questions/27509/detecting-an-undefined-object-property-in-javascript – dsgriffin Mar 26 '13 at 09:35

2 Answers2

26

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.')
}
romainberger
  • 4,563
  • 2
  • 35
  • 51
7
if (typeof marcamillion === 'undefined') {
    console.log("Marcamillion is an undefined variable.");
}

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

Fabien
  • 12,486
  • 9
  • 44
  • 62
  • Say I have an attribute that I am trying to test the value of - i.e. `$(this).attr('value')`...what would be the best way to determine if that is undefined? – marcamillion Mar 26 '13 at 09:43