How to check if tag exists using javascript without getting error

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

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

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

+4
source share
2 answers

Why not just check 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"); } 
+9
source

Try:

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

if you are not sure if myfile exists as an element, you should check this first:

 if (typeof myfile !== 'undefined' && myfile.getElementsByTagName && myfile.getElementsByTagName("client").length) {} 
+3
source

All Articles