Get Specific Class name start with something

Get all classes that start with btn:



<ul>
<li class="etape btn-one others"></li>
<li class="etape btn-two others"></li>
<li class="etape btn-three others"></li>
</ul>

This function get all classes separated by space then you can get what you want


	$('ul li').each(function(){
		var get = $.grep(this.className.split(" "), function(v, i){
		   return v.indexOf('btn') === 0;
		}).join();
		console.log(get);
	});

This code will return all classes with btn

Result:
btn-one
btn-two
btn-three

Other way to do that

$('ul li').each(function(){
	var myClass;
	
	// classNames will contain all applied classes
	var classNames = $(this).attr('class').split(/\s+/);  
      
	// iterate over all class  
    $.each(classNames, function(index, item) {
		// Find class that starts with btn-
		if(item.indexOf("btn-") == 0){
			// Store it
			myClass = item;
			console.log(myClass);
		}
    });
});

Working Example

5 thoughts on “Get Specific Class name start with something

Leave a comment