0

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 cols 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.

1
  • 2
    Why don't you add another has-width class that you can search for exactly, instead of searching for a pattern? Commented May 7, 2014 at 23:57

1 Answer 1

3

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

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

8 Comments

so simple... Thank you! I am using it like so: var numColsWidth = $(this).children('[class*="width"]').length; It takes 10 minutes to "accept an answer" but this will be accepted then
This will probably solve your problem, but beware. If you also have a class like fixed-width it will match that as well.
How so? look closely at my solution. there is a hyphen at the end of width, so it will not match fixed-width
good point. I will probably just change "width-" to a unique keyword in which case, this should do fine.
I think he meant if there's a class like this-width-fixed it will call it out. I think it can be fixed by saying $('[class*=" width-"]') with a space infront of the width
|

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.