Jquery selector to select all dropdown lists with ID pattern

What is the easiest way to iterate over all the dropdowns with an identifier matching a pattern using jquery. eg:

<select id="begin_1_end">...</select> <select id="begin_32_end">...</select> <select id="begin_42_end">...</select> <select id="dontgetme_2_end">...</select> <select id="begin_12_dontgetme">...</select> 

to iterate over the first three only.

+7
jquery jquery-selectors select
source share
3 answers

Try this with attribute-starts-with-selector /

 $('select[id^="begin"]').each(function () { console.log(this.id); }); 

or you can use attribute-ends-with-selector

 $('select[id$="end"]').each(function () { console.log(this.id); }); 

Update

To select the first 3 you can use :lt(3) , like this

 $('select[id^="begin"]:lt(3)').each(function () { console.log(this.id); }); 

Demo

Update

To combine selectors you can do this

 $('select[id^="begin"][id$="end"]').each(function () { console.log(this.id); }); 

Demo

If you want to select an element with an identifier starting at the beginning of OR , you can do this using, to get two different selectors

 $('select[id^="begin"],select[id$="end"]').each(function () { // ^ console.log(this.id); }); 

Demo

+23
source share

Use an attribute begins with a selector , and then use . each () to iterate through them

 $('select[id^=begin_]').each(function(){...}) 
+3
source share

Try using the attribute starts with a selector

  $("select[id^='begin_'").each(function(){ //your stuff }) 
+1
source share

All Articles