VanillaJS-通过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不是一个函数">

有关在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>

使用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>

您还可以将整个操作组合为一个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>

这意味着:

对于ID为edit_pickup_date_modal的元素内的每个input[name=type],为其value属性分配常数值2。

最新更新