一.getElementById方法
<head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> <script type="text/javascript" > function showText() { var oText = document.getElementById("my_text");//得到文本框元素 oText.value = "haha";//向文本框中赋值 } </script> </head> <body> <input type="text" id="my_text" /> <input type="button" οnclick="showText()" value="向文本框中赋值" /> </body>
二.getElementsByName方法
<head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> <script type="text/javascript" > function showText() { var oText = document.getElementsByName("txt");//得到所有name为txt的元素集合 for(var i = 0; i < oText.length; i++) { oText[i].value = i; } } </script> </head> <body> <input type="text" name="txt" /> <input type="text" name="txt" /> <input type="text" name="txt" /> <input type="text" name="txt" /> <input type="text" name="txt" /> <input type="text" name="txt" /> <input type="button" οnclick="showText()" value="向文本框中赋值" /> </body>
三.getElementsByTagName方法
<title>无标题文档</title> <script type="text/javascript" > function showText() { var oText = document.getElementsByTagName("input");//得到所有input对象 for(var i = 0; i < oText.length; i++) { alert(oText[i].type);//显示该节点的类型 } } </script> </head> <body> <input type="text" name="txt" /> <input type="checkbox" name="cb" /> <input type="password" name="pwd" /> <input type="button" οnclick="showText()" value="显示" /> </body>