Vanilla JS - 通过 div 的名称获取元素

Vanilla JS - Get element by name of a div

我需要在 JavaScript 中翻译此 jQuery 命令:

$('#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 不是函数”

使用getElementById获取id为'edit_pickup_date_modal'的标签。比使用 querySelector 搜索名称 = 'type' 的第一个 INPUT-field 并设置值。

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

更多关于搜索DOM上的元素的信息,例如getElementByIdquerySelector,请参考here

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>

您也可以将整个操作合并为一个 querySelector

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

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>
 

这意味着:

for each input[name=type] inside the element with the ID edit_pickup_date_modal, assign to its value property the constant value 2.