admin管理员组

文章数量:1201561

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.

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.

Share Improve this question edited Jan 4, 2013 at 22:41 VoltzRoad asked Dec 24, 2012 at 6:29 VoltzRoadVoltzRoad 4952 gold badges6 silver badges11 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 18

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");
}

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) {}

本文标签: xmlhow to check if a tag exists using javascript without getting an errorStack Overflow