2

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-*"'));
});
ahmad.ideveloper
  • 186
  • 1
  • 2
  • 11
  • 3
    This seems like a duplicate of http://stackoverflow.com/questions/5376431/wildcards-in-jquery-selectors – Asher Nov 08 '16 at 05:56

3 Answers3

3

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>
Satpal
  • 132,252
  • 13
  • 159
  • 168
1

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>
four
  • 564
  • 4
  • 6
0

You have to give the star after the double quotes like this,

alert($(this).attr('class^="cc-"*'));
GraveyardQueen
  • 771
  • 1
  • 7
  • 17