如何使用纯原生JavaScript清除指定DIV内所有class为axs的input字段值
问题分析
你当前的代码不生效的核心原因是:你把#output的HTML内容复制到了内存中新建的div元素里修改,所有操作都没有作用在页面实际渲染的DOM节点上,改动不会同步到页面。
完整实现方案
HTML部分
新增触发清空的按钮,保留你原有结构即可:
<button id="clearAxsBtn">清空指定输入框</button> <div id="output"> <div> <input class="axs" id="1" type="text" value="1650" spellcheck="false"> <input class="axs" id="2" type="text" value="850" spellcheck="false"> <input class="axs" id="3" type="text" value="340" spellcheck="false"> <input class="axs" id="4" type="text" value="321" spellcheck="false"> <input class="axs" id="5" type="text" value="567" spellcheck="false"> <input class="axs" id="6" type="text" value="890" spellcheck="false"> </div> </div>
JS部分
直接选中页面中的目标元素进行修改即可:
// 绑定按钮点击事件 document.getElementById('clearAxsBtn').addEventListener('click', function() { // 选中#output下所有class为axs的input const targetInputs = document.querySelectorAll('#output input.axs'); // 遍历清空值 targetInputs.forEach(input => { // 修改DOM对象的value属性,即时生效 input.value = ''; // 如果需要同步修改HTML标签上的value属性值,可加下面这行 // input.setAttribute('value', '') }) })
内容的提问来源于stack exchange,提问作者Ayush Kangar
相关产品推荐
相关产品推荐

