javascript – How to select a select type object which has certain text in the id in vanilla js?-ThrowExceptions

Exception or error:

I have html elements which have keyword ‘target’ in their ids. I want to select a ‘select’ elements which contain the key word in their id.

<select id="page_blocks_0_buttons_1_target"><option value=""></option></select>
<select id="page_blocks_0_buttons_2_target"><option value=""></option></select>
<select id="page_blocks_0_buttons_3_target"><option value=""></option></select>
<select id="page_blocks_0_buttons_4_target"><option value=""></option></select>
<div id="page_target_div"></div>

My current attempt is as follow, but it also returns the div type which i don’t want.

var targetFields = document.querySelectorAll("*[id*=target]");
How to solve:

querySelectorAll expects a CSS selector– you are prefixing with *, which will select all elements– change it to select and it should work as expected. See the snippet below:

var targetFields = document.querySelectorAll("select[id*=target]");
console.log(targetFields)
<select id="page_blocks_0_buttons_1_target"><option value=""></option></select>
<select id="page_blocks_0_buttons_2_target"><option value=""></option></select>
<select id="page_blocks_0_buttons_3_target"><option value=""></option></select>
<select id="page_blocks_0_buttons_4_target"><option value=""></option></select>
<div id="page_target_div"></div>

###

Use :not to avoid div.

var targetFields = document.querySelectorAll("*[id*=target]:not(div)");
console.log(targetFields.length);
<select id="page_blocks_0_buttons_1_target">
  <option value=""></option>
</select>
<select id="page_blocks_0_buttons_2_target">
  <option value=""></option>
</select>
<select id="page_blocks_0_buttons_3_target">
  <option value=""></option>
</select>
<select id="page_blocks_0_buttons_4_target">
  <option value=""></option>
</select>
<div id="page_target_div"></div>

Leave a Reply

Your email address will not be published. Required fields are marked *