how to check if a tag exists using javascript without getting an error

25,293

Solution 1

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

Solution 2

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) {}
Share:
25,293
VoltzRoad
Author by

VoltzRoad

I believe in science

Updated on January 05, 2020

Comments

  • VoltzRoad
    VoltzRoad over 4 years

    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.