Youss
Youss

Reputation: 4222

Doing 'if statement' gives strange result in console

I'm doing an if statement using the presence of a global variable. The variable:

 _class = $('a').parent().closest('*[class]')[0].className; 

In this case there is no parent and so there is no class. I would like to recieve this info in the console, so I did an if statement:

if ( _class !== undefined ) {

    console.log('has class');

}else{

    console.log('undefined');

} 

In Chrome inspector I'm getting Uncaught TypeError: Cannot read property 'className' of undefined and nothing else regarding my if statement. My question: what can I do to get rid of the error message and output my if statement? I tried it with null and length and so on, nothing seems to work.

Example: JsFiddle

Upvotes: 1

Views: 64

Answers (5)

Aziz
Aziz

Reputation: 171

It's because you try to find className of jQuery Object. But className - it's method for DOM elements, which often returns with simple javascript method, for example getElementById and so. If you work with jQuery Object, use jquery methods for it, and in this case methid .attr('class');

Upvotes: 1

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

Try to handle that error,

 _class = $('a').parent().closest('*[class]')[0] || "NOPE";

 if (_class === "NOPE") {
     console.log('undefined');
 } else {
     if (_class.className !== undefined) {
         console.log('has class');
     } else {
         console.log('undefined');
     }
 }

DEMO

Upvotes: 4

florin.prisecariu
florin.prisecariu

Reputation: 422

first check if you select at least an element

   elements = $('a').parent().closest('*[class]');

    if (elements.length > 0) {
       _class = elements[0].className; 
       if ( _class !== undefined ) {
          console.log('has class');
       }else{
          console.log('undefined');
       }
    }
    else {
       console.log('no element found');
    }

Upvotes: 2

A. Wolff
A. Wolff

Reputation: 74420

You should check for element existence before trying to get className property:

_class = $('a').parent().closest('*[class]').length ? $('a').parent().closest('*[class]')[0].className : undefined; 

Upvotes: 3

Ben
Ben

Reputation: 7597

The issue is with your global assignment: the code doesn't get as far as your if statement. You're trying to derive a property from a null reference -- that could be parent or the result of your closest call. You need to do some checking around that initial assignment.

Upvotes: 3

Related Questions