kusanagi kusanagi - 2 months ago 7
Javascript Question

Jquery how to separate selector

I have such code

$('select[name$="[country_id]"], select[name$="[region_id]"], select[name$="[city_id]"]').select2();


I try to rewrite it to

$('select').find('[name$="[country_id]"], [name$="[region_id]"], [name$="[city_id]"]').select2();


but not works. Is any solution?

Answer

Use .filter(); .find() selects child elements of selector

console.log(
  $('select')
  .filter('[name$="[country_id]"], [name$="[region_id]"], [name$="[city_id]"]'))
//  .select2();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="name_[country_id]">
  </select>
<select name="name_[region_id]">
  </select>
<select name="name_[city_id]">
  </select>
<select name="name_[not_city_id]">
  </select>
<select name="name_[not_region_id]">
  </select>