-3

Without using JQuery how would I convert

$('#H10 option[value*="2"]').attr('selected',true).trigger('change')

into vanilla Javascript. I believe using dispatchEvent(new Event('')) would replace trigger() but I cant find anything for the attr() function. When I tried to use :

document.querySelector('#H10 option[value*="2"]').setAttribute('selected', 'selected').dispatchEvent(new Event('change'))

I get Uncaught TypeError: Cannot read properties of undefined (reading 'dispatchEvent'). Other things I have tried include using the selected() = true.

Any help appreciated.

HN117
  • 1
  • 2

1 Answers1

1

Unlike jQuery's methods, all DOM methods don't return this necessarily, setAttribute() for instance returns undefined.
This means that you can't chain your calls like you were doing in jQuery.

You should store your element in a variable, set its attribute, and then call its dispatchEvent method.

const option = document.querySelector('#H10 option[value*="2"]');
option.setAttribute('selected', 'selected');
option.dispatchEvent(new Event('change'));
<div id="H10">
  <select>
    <option value="abc">abc</option>
    <option value="123">123</option>
  </select>
</div>
Kaiido
  • 123,334
  • 13
  • 219
  • 285