7

I have xml data with root "clients" and it can contains multiple elements of "client" inside it. sometimes there are no client elements that are returned in the XML file (this is ok). I need to determine if there are any client elements returned so i tried using:

if(typeof myfile.getElementsByTagName("client")){
  alert("no clients");
}

This does the intended job, but I get a firebug error whenever there are no "client" elements.

VoltzRoad
  • 475
  • 2
  • 6
  • 11

2 Answers2

17

Why not just check for the length of the NodeList?

if( myfile.getElementsByTagName("client").length == 0 )
{
 alert("no clients");
}

Add this to check if myfile has been defined

if( typeof myfile == "undefined" || myfile.getElementsByTagName("client").length == 0 )
{
 alert("no clients");
}
Travis J
  • 81,153
  • 41
  • 202
  • 273
  • it still makes an error message that says 'null' is not an object – VoltzRoad Dec 24 '12 at 06:36
  • @VoltzRoad - Is `myfile` null? If you run this in the console for this page `if( document.getElementsByTagName("client").length == 0 ) { alert("no clients"); }` it will alert "no clients". – Travis J Dec 24 '12 at 06:39
  • 1
    ok you are right. basically the file was coming in as completely empty when there were no clients. So it wasn't any longer a legit xml document. Thanks for first answer though. it helped me isolate the problem. – VoltzRoad Dec 24 '12 at 06:51
  • @VoltzRoad - Glad you got it figured out :) – Travis J Dec 24 '12 at 06:53
3

Try:

if (!myfile.getElementsByTagName("client").length) {}
//                                          ^ falsy (0) if no elements

if you're not sure myfile exists as an element you should check for that first:

if (typeof myfile !== 'undefined'
    && myfile.getElementsByTagName 
    && myfile.getElementsByTagName("client").length) {}
KooiInc
  • 119,216
  • 31
  • 141
  • 177