Ahmad
Ahmad

Reputation: 186

CSS class selector jQuery with specific Class name

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

Answers (3)

four
four

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

Satpal
Satpal

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

GraveyardQueen
GraveyardQueen

Reputation: 769

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

alert($(this).attr('class^="cc-"*'));

Upvotes: 0

Related Questions