Reputation: 303
In the following code sample, typeof item === "undefined" never returns true. i am trying to get an attribute from XML, if the attribute is not there in the XML it returns "undefined", but i am not able to capture whether it has returned undefined or not, firebug shows "typeof item" as an "object"
var item;
var itemIDs = {};
if (items.status == 200)
{
var rows = items.responseXML.getElementsByTagName('z:row');
for(i=0;i<rows.length;i++)
{
//rows[i].attr(attribute);
item = rows[i].getAttribute(attribute);
if(typeof item === "undefined")
{
continue;
}
else
{
item = item.match(/[^\d+;#][\w\W]+/);
itemIDs[item] = 1 ;
}
}
}
else
{
alert('There was an error: ' + items.statusText);
}
return itemIDs;
Edit: I changed the condition to if(item == undefined), The code now works as expected now
Edit2: Double checked it, item variable was never null , it was "undefined"
Upvotes: 0
Views: 1543
Reputation: 272096
typeof null
is "object"
... this is what getAttribute seems to return when the attribute is missing. See documentation of element.getAttribute, specifically the notes section. It is suggested that you can use hasAttribute.
Upvotes: 1
Reputation: 42099
getAttribute
: return type object
you should compare return value to null
Upvotes: 0
Reputation: 4213
Some browser's implementation of getAttribute
may return an empty string if the attribute doesn't exist. You could test for both null and ""
, or alternatively use hasAttribute
.
if(rows[i].hasAttribute(attribute))
{
// do stuff...
}
https://developer.mozilla.org/en/DOM/element.getAttribute
Upvotes: 2
Reputation: 79
try this:
if (!item)
{
continue;
}
else
{
item = item.match(/[^\d+;#][\w\W]+/);
itemIDs[item] = 1 ;
}
this proofs if the item is null or undefined. is this true, it continues the loop.
Upvotes: 0
Reputation: 14885
getAttribute returns an object (valid object or a null object). So the check (typeof item === "undefined")
is not correct. It should be (item === null)
.
Upvotes: 3
Reputation: 17899
It's because typeof null === 'object'
(contrary to the common sense). You should check if getAttrbiute
's return value equals null
.
item = rows[i].getAttribute(attribute);
if (item == null) { /* ... */ }
Upvotes: 1