Javascript "Cannot read property 'length' of undefined" when checking a variable's length -
i'm building node
scraper uses cheerio
parse dom
. more or vanilla javascript question though. @ 1 part of scrape, i'm loading content variable, checking variable's length
, so:
var thehref = $(obj.mainimg_select).attr('href'); if(thehref.length){ // stuff }else{ // other stuff }
this works fine, until came across url $(obj.mainimg_select).attr('href')
didn't exist. assumed thehref.length
check account , skip through else: other stuff
statement, instead got:
typeerror: cannot read property 'length' of undefined
what doing wrong here , how can fix this?
you can check thehref
defined checking against undefined.
if (undefined !== thehref && thehref.length) { // `thehref` not undefined , has truthy property _length_ // stuff } else { // other stuff }
if want protect against falsey values null
check thehref
truthy, little shorter
if (thehref && thehref.length) { // `thehref` truthy , has truthy property _length_ }
Comments
Post a Comment