0

I'm using jQuery to scan a page, find all the links on the page, and if they have a "title" attribute, output them in the console log.

$("a").each(function () {
    var title = $(this).attr('title');
    if (title !== 'undefined') {
        console.log(title + 'blah');
    }
})

What I cannot understand is that it outputs "undefined" many times as well, despite me specifying that it should not log anything with this value:

if(title !== 'undefined'){
    console.log(title+'blah');
}

Here is an example of the console.log results:

undefinedblah
About WordPressblah
undefinedblah
comments awaiting moderationblah
Newblah
undefinedblah
My Accountblah
undefinedblah

Why are all these undefined options passing my if statement?

Shaunak D
  • 20,588
  • 10
  • 46
  • 79
Francesca
  • 26,842
  • 28
  • 90
  • 153

3 Answers3

1

Just use

if(title){
    console.log(title+'blah');
}

It checks for truthy value. The value is undefined and not 'undefined'

title would be falsy under null, undefined, 0, "" and false


Side note, why not use attribute selector; it would omit the as without title

$("a[title]").each(function () {
    var title = $(this).attr('title');
    console.log(title + 'blah');
})
Shaunak D
  • 20,588
  • 10
  • 46
  • 79
0

If you want to explicitly check that the type is not undefined use typeof. At the moment you are checking that the type of variable is "string" and its value is "undefined".

if(typeof title !== "undefined") {
    // Code
}
David Barker
  • 14,484
  • 3
  • 48
  • 77
0

Instead of using "undefined" use undefined.

$(document).ready(function () {
    $("div a").each(function () {
        var value = $(this).prop("title");
        console.log(value);
        if (value !== undefined) console.log("title: "+value);
    });
});

For more information check this Link.

Sukanya1991
  • 778
  • 3
  • 17