Jose Bernhardt Jose Bernhardt - 1 month ago 11
Javascript Question

Select option with cheerio (jquery) by text

I'm trying to select an option from a select dropdown with the

attribute of the HTML element with
. So far what I'm doing is that I'm trying to set the
as selected matching, the element with the specific text.

This is what I'm trying:

$('#ddl_city option[text="testing"]').attr('selected', 'selected');

I'm not getting any changes on the html when I do this. I print the html document on the console after doing this operation and I don't see that the option has changed to the one I'm selecting. Any idea why is not working or another workaround?


You can use the :contains filter to get the specific option element based on the text and set the value of the select element to it's value:

$('#s1').val($("#s1 option:contains('Val B')").val())
<script src=""></script>
<select id="s1">
  <option value="a">Val A</option>
  <option value="b">Val B</option>