Find items with class and id

You can scroll through all the elements where the Example idcontains med_date:

$( $('[id^=med_date_]') ).each(function() {

Can you do it with idand class, something like this

$( $('[id^=med_date_] [class^=med_group_]') ).each(function() {

The identifier may be med_date_1, med_date_2, med_date_3, etc
the same for the classmed_group_1, med_group_2, med_group_3, etc.

+4
source share
4 answers

Yes, you should simply remove the space between the selectors, for example:

$('[id^=med_date_][class^=med_group_]')

To selector for class AND id , if you want class OR id , you can use comma separator:

$('[id^=med_date_],[class^=med_group_]')

Hope this helps.

$( $('[id^=med_date_][class^=med_group_]') ).each(function() {
   console.log($(this).text());  
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<span id='med_date_1' class='med_group_1'>Span 1</span>
<br>
<span id='med_date_2' class='med_group_2'>Span 2</span>
<br>
<span id='med_date_3' class='med_group_3'>Span 3</span>
Run codeHide result
+3
source

. , , , Descendant Selector ("ancestor descendant")

$('[id^=med_date_][class^=med_group_]').doSomething()

$('[id^=med_date_][class^=med_group_]').css('color', 'green')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id='med_date_1' class='med_group_1'>Span 1</span>
<br>
<span id='med_date_2' class='med_group_2'>Span 2</span>
<br>
<span id='med_date_3' class='med_group_3'>Span 3</span>
Hide result
+2

If you want to select all the elements in which idit classcontains some substring, you can use the attribute selector [attr*=value].

$('[id*="med_date_"][class*="med_date_"]')

$('[id*="med_date_"][class*="med_date_"]').css('color', 'red')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="other med_date_2" id="med_date_1">Div</div>
<div class="med_date_2 other" id="med_date_2">Div</div>
Run codeHide result

If you use a selector [class^="med_date_"]which means that the class value should start with med_date_, so it will not work if you have an element with a class like this class="other med_date_2", as you can see here

$('[id^="med_date_"][class^="med_date_"]').css('color', 'red')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="other med_date_2" id="med_date_1">Div</div>
<div class="med_date_2 other" id="med_date_2">Div</div>
Run codeHide result
+2
source

Use this:

$("[id^=med_date_], [class^=med_group_]")
0
source

Source: https://habr.com/ru/post/1668731/


All Articles