实例1:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>getElementsByName</title> </head> <body > <p name="pr" ff="pr"> aaa </p> <p name="pr" ff="pr"> bbb </p> <p name="pr" ff="pr"> ccc </p> <p name="pr" ff="pr"> ddd </p> <p name="pr" ff="pr"> eee </p> <p name="pr" ff="pr"> eee </p> <p name="pr" > eee </p> <p name="pr" > eee </p> <input type="button" onclick="myFun()" value="按钮"/> </body> <script type="text/javascript" > function myFun() { var count = 0; var pArr = document.getElementsByTagName_r("p"); for(var i=0;i<pArr.length;i++) { var p = pArr[i]; if (p.getAttribute("ff") == "pr" ) { count++;// 符合要求的p标签数目 } } alert(count); } </script> </html>
实例2:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>getElementsByName2[拿到name是pr的p标签对象数组]</title> </head> <body > <p name="pr" ff="pr"> aaa </p> <p name="pr" ff="pr"> bbb </p> <p name="pr" ff="pr"> ccc </p> <p name="pr" ff="pr"> ddd </p> <p name="pr" ff="pr"> eee </p> <p name="pr" > eee </p> <p name="pr" > eee </p> <p name="pr" > eee </p> <input type="button" onclick="myFun()" value="按钮"/> </body> <script type="text/javascript"> var getElementsByName = function(name){ var rets = document.getElementsByName(name); if(rets.length == 0) { rets = []; var alls = document.getElementsByTagName_r("*"); for(var i=0;i<alls.length ; i++) { if(alls[i].getAttribute("name") == name) { rets.push(alls[i]); } } } return rets; }; function myFun() { var res = getElementsByName("pr"); alert(res.length); } </script> </html>