JS获取指定类名下的input/div/button等特定元素

<body>
   
    <!-- 获取指定类名下的所有input元素 -->
    <div class="aCuteName">
        <div></div>
        <input type="text" value='1'>
        <input type="text" value='2'>
        <ul>
            <li>3</li>
            <li>4</li>
            <li>5</li>
        </ul>
        <input type="text" value='3'>
        <input type="text" value='4'>
        <input type="text" value='5'>
        <button>别点我</button>
    </div>
    <div>
        哈哇油
    </div>
    <div>
        <button>玩不一块儿去</button>
        <div>颜值即正义</div>
        <input type="text" value="不在获取范围">
    </div>
    <div class="aCuteName">
        <div>水月洞天YYDS</div>
        <input type="text" value='a'>
        <input type="text" value='b'>
        <button>滚粗</button>
    </div>
    
    <script>
        // 获取指定类名下的指定元素
    let grandfather = document.getElementsByClassName('aCuteName');//获取所有类名为aCuteName的元素
    let children = []//用来接收要获取的数据
    for (let i of grandfather) {
        let father = i.childNodes;//获取每个类名为aCuteName元素的子元素合集
        for (let j in father) {
            if (father[j].localName === "input")//通过localName获取input元素合集
                children.push(father[j]);//将所有input保存在一个数组中
        }
    }
    console.log(children);
    children[5].value = '这是一个暗号'
   </script>

</body>

 

 // 函数封装 获取指定类名下的所有指定元素
    const getElementsByLocalNameOfClassName = function (className, elementName) {
        let grandfather = document.getElementsByClassName(`${className}`);//获取所有类名为aCuteName的元素
        let children = []//用来接收要获取的数据
        for (let i of grandfather) {
            let father = i.childNodes;//获取每个类名为aCuteName元素的子元素合集
            for (let j in father) {
                if (father[j].localName === `${elementName}`)//通过localName获取input元素合集
                    children.push(father[j]);//将所有input保存在一个数组中
            }
        }
        return children
    }
    let inputsOfaCuteName = getElementsByLocalNameOfClassName('aCuteName','input')//获取类名为aCuteName元素下的所有input元素
    console.log(inputsOfaCuteName[4].value);//打印获取到的第5个input的值

  

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值