Javascript 如何使用javascript检查标签是否存在而不会出错
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14017864/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to check if a tag exists using javascript without getting an error
提问by VoltzRoad
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:
我有根“clients”的xml数据,它可以在其中包含多个“client”元素。有时在 XML 文件中没有返回客户端元素(这是可以的)。我需要确定是否有任何客户端元素返回,所以我尝试使用:
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.
这完成了预期的工作,但是只要没有“客户端”元素,就会出现萤火虫错误。
回答by Travis J
Why not just check for the length of the NodeList?
为什么不只检查 NodeList 的长度?
if( myfile.getElementsByTagName("client").length == 0 )
{
alert("no clients");
}
Add this to check if myfile has been defined
添加此项以检查是否已定义 myfile
if( typeof myfile == "undefined" || myfile.getElementsByTagName("client").length == 0 )
{
alert("no clients");
}
回答by KooiInc
Try:
尝试:
if (!myfile.getElementsByTagName("client").length) {}
// ^ falsy (0) if no elements
if you're not sure myfileexists as an element you should check for that first:
如果您不确定是否myfile作为元素存在,您应该先检查一下:
if (typeof myfile !== 'undefined'
&& myfile.getElementsByTagName
&& myfile.getElementsByTagName("client").length) {}

