简体   繁体   中英

How to select element that has a certain class and has a class that ends with?

I have the following code

<span id="student" class="studentTrainingActive selected-for">Foo bar</span>

How to select it?

According to this answer I have tried to use the following code:

$('span[class$="TrainingActive"].selected-for').length

But the result is always 0.

What's wrong with my code?

You just have a minor issue with your selector.

class$="TrainingActive"

Should actually be:

class*="TrainingActive"

Resulting code:

 console.log($('span[class*="TrainingActive"].selected-for').length);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <span id="student" class="studentTrainingActive selected-for">Foo bar</span>

Outputs in console:

1

Why Use *= and not $=

As helpfully pointed out by @Andreas, the reason that $= as a selector is not working is because the class does not end with TrainingActive . Look at the class attribute:

studentTrainingActive selected-for

It ends with selected-for .

Using contains ( *= ) instead will happily match the class as required and can of course be combined with .selected-for as you require.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM