javascriptjquerygetelementsbyname

Vanilla JS - Get element by name of a div


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"


Solution

  • 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>