Reputation: 5985
I am trying to get the number of elements that have a certain class name in them, the problem is, this class name has a variable at the end of it. For example:
<div class="row">
<div class="col">
</div>
<div class="col width-33">
</div>
<div class="col">
</div>
</div>
I have been trying to write a jquery script to get the number of different col
s there are and to get the number of columns with a class name of width-xx
where XX can be any number.
$('.col').parent().each(function(i){ //The container could be anything
var numCols = $(this).children('.col').length;
var numColsWidth = $(this).children('div[class^="width-"].col').length;
console.log(numCols, numColsWidth);
});
I'd like to output to be 3 1
, showing there are 3 total columns and 1 of them has a class named width-xx.
Just as the example above shows, I've tried using the CSS selector, but that doesn't give me anything (outputs 3 0
)
I've also tried playing around with RegExp, but I'm not sure how to add this into that
var widthClass = new RegExp("width-");
if(widthClass.test($('.col').attr('class'))){
//do something
}
So, all I would like to do is count the number of elements that contain the word "width-" in the class.
Upvotes: 0
Views: 2587
Reputation: 1450
$('[class*="width-"]').length
should do it.
this selector allows you to find any element that countains the word "width-" in the class
Upvotes: 3