English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
1Find all elements with the given name attribute, this method will return a node collection, which can also be called an object collection.
2This collection can be treated as an array, the value of the length property indicates the number of elements in the collection.
3Because in the HTML page, name cannot uniquely determine an element, so the method name is getElementsByName instead of getElementByName
<!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>Untitled Document</title> </head> <body> <p> <input type="text" name="luck" value="I won the lottery, and won a billion yuan" onclick="aa()" id="luck1" /> </p> <p> <input type="text" name="luck" value="I got a girlfriend" id="luck2" /> </p> <p> <input type="text" name="luck" value="I was promoted" id="luck3" /> </p> <p> <input type="text" name="luck" value="I bought a house" id="luck4" /> </p> <script> /* 1Get the value of each text box 2Get the type of each text box 3Add a click event to each text box */ /* First step: Get the object array (node array) with the name attribute value of luck */ var luckElements = document.getElementsByName("luck"); /* Second step: Traverse the node array */ for(var i=0;i<luckElements.length;i++{ //Get the element's value alert(luckElements[i].value); //Get the element's type value alert(luckElements[i].type); //Assigning the onclick attribute to each element is to add a click event to the text box luckElements[i].onclick=function(){ alert(this.value); } } </script> </body> </html>
3Because in the HTML page, name cannot uniquely determine an element, so the method name is getElementsByName instead of getElementByName
That's all for the method of accessing the name collection object in JavaScript through getElementsByName that the editor has brought to you. I hope everyone will support and cheer for the tutorial~