简体   繁体   中英

jQuery find elements with variable class names using regex?

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.

$('[class*="width-"]').length should do it.
this selector allows you to find any element that countains the word "width-" in the class

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM