纯JavaScript - 根据div的名称获取元素

5

我需要将以下jQuery命令翻译成JavaScript:

$('#edit_pickup_date_modal').find('input[name=type]').val('2');

我尝试着:

var element = document.getElementById('edit_pickup_date_modal');
var input = element.getElementsByName('type')[0];
input.value = '2'

但是我遇到了错误 "element.getElementsByName 不是一个函数"。

1
JavaScript通过名称获取子元素 - Nathan Champion
1
你尝试过这个代码吗?var elms = document.querySelectorAll('#edit_pickup_date_modal input[name=type]'); elms.forEach(x => { x.value = 2 } )? 或许在你使用的最老的浏览器上,你需要将 Element.prototype.querySelectorAll 返回的 NodeList 强制转换为普通的 Array,可以使用 Array.from(elms) - asdru
4个回答

4

如果想要查找DOM上的元素,例如getElementByIdquerySelector,请参见此处了解更多信息。

const modalDiv = document.getElementById('edit_pickup_date_modal')

const inputElem = modalDiv.querySelector('input[name=type]');

inputElem.value = 2
<div id="edit_pickup_date_modal">
  <input name="type"/>
</div>


3
使用 getElementById 获取 id 为 'edit_pickup_date_modal' 的标签。然后使用 querySelector 查找第一个名称为 'type' 的 INPUT 字段,并设置其值。

document.getElementById('edit_pickup_date_modal').querySelector('input[name=type]').value=2;
<div id='edit_pickup_date_modal'>
  <div>
    <input name ='type'>
  </div>
</div>


1

You can also combine the whole operation into a single querySelector:

document.querySelector('#edit_pickup_date_modal input[name=type]').value=2;
<div id='edit_pickup_date_modal'>
  <div>
    <input name ='type'>
  </div>
</div>


1

对于 jQuery 中的 $('#edit_pickup_date_modal').find('input[name=type]').val('2');,其等效的普通函数为:

document.querySelectorAll('#edit_pickup_date_modal input[name=type]').forEach(function(obj, index){
    obj.value=2;
});

//If you need to take the first element only.
document.querySelector('#edit_pickup_date_modal input[name=type]').value=3;
<div id="edit_pickup_date_modal">
  <input name="type"/>
   <input name="type"/>
    <input name="type"/>
     <input name="type"/>
</div>
 

这意味着:

针对ID为edit_pickup_date_modal的元素内的每个input[name=type],将其value属性赋值为常量2。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接