Reputation: 186
I want to get Class starting with specific string in jQuery
<li class="active cc-1">A1</li>
<li class="cc-2">B1</li>
<li class="cc-ab amimate-me">C1</li>
how can I select class starts with "cc-ANYTHING" ON CLICK of "<li>"
$('li').on('click', function(e){
alert($(this).attr('class^="cc-*"'));
});
Upvotes: 2
Views: 108
Reputation: 564
Another method using .attr('class')
together with Array.prototype.filter()
:
$('li').on('click', function(e) {
var classlist = $(this).attr('class');
if (classlist === undefined) { // check if li doesn't have a class attribute
return false;
}
// filter and return the class if it starts with 'cc-'
var ccClass = classlist.split(' ').filter((v, i) => (v.startsWith('cc-')));
console.log(ccClass);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li class="active cc-1">A1</li>
<li class="cc-2">B1</li>
<li class="cc-ab amimate-me">C1</li>
<li>D1</li>
<li class="animate-me">E1</li>
</ul>
Upvotes: 1
Reputation: 133453
You can use Element.classList property to iterate the collection of the class attributes of the element. and String.prototype.startsWith() can be used to test.
Here in the example, since multiple class can fulfill the condition Array
is used.
jQuery(function($) {
$('li').on('click', function(e) {
var arr = []
for (var i = 0; i < this.classList.length; i++) {
var item = this.classList.item(i);
if (item.startsWith("cc-")) {
arr.push(item);
}
}
console.clear();
console.log(arr);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li class="active cc-1">A1</li>
<li class="cc-2">B1</li>
<li class="cc-ab amimate-me">C1</li>
</ul>
Upvotes: 3
Reputation: 769
You have to give the star after the double quotes like this,
alert($(this).attr('class^="cc-"*'));
Upvotes: 0