Vanilla JS - Get element by name of a div

7.7k views Asked by At

I need to translate this jQuery command in JavaScript:

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

I tried to:

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

but I got the error "element.getElementsByName is not a function"

4

There are 4 answers

0
Sascha On BEST ANSWER

Use getElementById to get the tag with id 'edit_pickup_date_modal'. Than search with querySelector for the first INPUT-field with name = 'type' and set the value.

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

0
Nithish On

For more info on searching for the elements on DOM such as getElementById, querySelector, please refer 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>

0
Daniel Beck On

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>

0
toto On

The equivalent vanilla function for the jQuery $('#edit_pickup_date_modal').find('input[name=type]').val('2');

is:

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>
 

And it means:

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