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-*"'));
});
1

3 Answers 3

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Good Technique *classList
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>

Comments

0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.