Home > Web Front-end > JS Tutorial > How to access the name collection object through getElementsByName in js

How to access the name collection object through getElementsByName in js

高洛峰
Release: 2016-12-08 13:24:50
Original
1729 people have browsed it

1. Find all elements with a given name attribute. This method will return a node collection, which can also be called an object collection.

2. This collection can be treated as an array, and the value of the length attribute represents the number of collections.

3. Because in the html page, name cannot uniquely determine an element, so the name of the method 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>无标题文档</title>
</head>
 
<body>
    <p>
        <input type="text" name="luck" value="我中奖了,中了一个亿" onclick="aa()" id="luck1" />
    </p>
    <p>
        <input type="text" name="luck" value="我交了女朋友" id="luck2" />
    </p>
    <p>
        <input type="text" name="luck" value="我升迁了" id="luck3" />
    </p>
    <p>
        <input type="text" name="luck" value="我买房了" id="luck4" />
    </p>
     
    <script>
        /*
        1、获取每一个文本框的值
        2、获取每一个文本框的类型
        3、为每一个文本框增加点击事件
        */
         
        /*
            第一步 获取name属性为luck值得对象数组(节点数组)
        */
        var luckElements = document.getElementsByName("luck");
         
        /*
            第二步 遍历节点数组
        */
        for(var i=0;i<luckElements.length;i++){
            //获取元素的value值
            alert(luckElements[i].value);
            //获取元素的type值
            alert(luckElements[i].type);
            //为每一个元素的onclick属性赋值即为文本框增加点击事件
            luckElements[i].onclick=function(){
                alert(this.value);
            }
        }
    </script>
</body>
</html>
Copy after login

3. Because in the html page, name cannot uniquely determine an element, so the method The name is getElementsByName instead of getElementByName


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template