How to count elements with a specific jquery class

I have elements with classes like dis_5

and dis_3

. If the part dis_

stays the same while the number changes. I want to count the elements with each number, for example if 3 elements are of class dis_5 then the elements are counted. Likewise for other dis_ as well.

var result = $('[class^=dis_]').filter(function () {
            return this.class.match(/dis_\d+$/); //regex for the pattern "rank_ followed by a number"
    });

      

How to combine elements with a specific number at the end.

+3


source to share


7 replies


Try it,

var classes={};
$('[class^=dis_]').each(function () {
    if(classes.hasOwnProperty(this.className)){
      classes[this.className]= classes[this.className]+1;
    } else {
      classes[this.className]=1;
    }
});

      

Excerpt



var classes = {};
$('[class^=dis_]').each(function() {
  if (classes.hasOwnProperty(this.className)) { // if classs exists then increment it by 1
    classes[this.className] = classes[this.className]+1;
  } else {
    classes[this.className] = 1; // first instance
  }
});
console.log(classes);
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dis_1">Class 1</div>
<div class="dis_1">Class 1</div>
<div class="dis_1">Class 1</div>
<div class="dis_5">Class 5</div>
<div class="dis_5">Class 5</div>
<div class="dis_2">Class 2</div>
<div class="dis_3">Class 3</div>
      

Run codeHide result


If you have multiple classes, try snippet



var classes = {};
$('[class*=dis_]').each(function() { // use *= selector, dis_ class can be used anywhere
  className = null;
  // get all classes and split to get match for dis_
  $.each($(this).attr('class').split(/\s+/), function(index, cls) {
    if (/dis_\d+/.test(cls)) {
      className = cls;
    }
  });
  // check if element having class started with dis_
  if (className) {
    if (classes.hasOwnProperty(className)) { // if classs exists then increment it by 1
      classes[className] = classes[className] + 1;
    } else {
      classes[className] = 1; // first instance
    }
  }
});
console.log(classes);
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dis_1">Class 1</div>
<div class="dis_1">Class 1</div>
<div class="dis_1 rehub_meta_field rehub_field_1 disabled disabled-0">Class 1</div>
<div class="dis_5">Class 5</div>
<div class="dis_5">Class 5</div>
<div class="dis_2">Class 2</div>
<div class="rehub_meta_field rehub_field_1 disabled disabled-0 dis_3">Class 3</div>
      

Run codeHide result


+2


source


Try it,

var lengthArr = []; // array to hold your result set

var YourNumberLimit = 5; // if you class is an incremental number with prefix "dis_", like dis_1, dis_2, dis_3, dis_4, dis_5

for (i=1;i<=YourNumberLimit ; i++) {

   lengthArr.push ( $(".dis_" + i).length); // your answer is here.

}

      



If this is not your case, and you need to calculate the length for induvidual classes, then use like this:

var lenthOfDis3 = $(".dis_5").length;
var lenthOfDis5 = $(".dis_5").length;
var lenthOfDis7 = $(".dis_5").length;
var lenthOfDis18 = $(".dis_5").length;

      

+2


source


jQuery(document).ready(function(){
		var classString = "";
		jQuery('[class^=dis_]').each(function(){
			var classData = jQuery(this).attr("class");
			var ClassDataChunk = classData.split("_");
			var classChunk = ClassDataChunk[1];
			var elmVal = jQuery("#elm").val();
			if (elmVal.indexOf(classChunk) < 0) {
				alert("Class dis_"+classChunk+" has count = " +jQuery(".dis_"+classChunk).length);
			}
			classString = classString + "," + classChunk;
			jQuery("#elm").val(classString);
		});
	});
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<input type="hidden" value="" name="elm" id="elm">
<div class="container">
	<div class="dis_3">3</div>
	<div class="dis_1">1</div>
	<div class="dis_1">1</div>
	<div class="dis_1">1</div>
	<div class="dis_1">1</div>
	<div class="dis_2">2</div>
	<div class="dis_2">2</div>
	<div class="dis_4">4</div>
	<div class="dis_3">3</div>
	<div class="dis_3">3</div>
</div>
      

Run codeHide result


+2


source


Try it. Hope it helps

  
  var arrClasses = [], uniqueClass = [];
$('[class^=dis_]').each(function () {
    var className = this.className.match(/dis_\d+/); 
    if (className) {
        arrClasses.push(className[0]); 
        return className[0]; 
    }
});
$.each(arrClasses, function(i, el){
   if($.inArray(el, uniqueClass) === -1) uniqueClass.push(el);
});
$.each(uniqueClass, function(i, el){
   var classLen = $('.'+el).length;
   console.log('Class: '+ el +'--- Length: '+ classLen);
});
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>


  <body >
<div class="dis_2">1</div>
<div class="dis_2">2</div>
<div class="dis_2">3</div>
<div class="dis_5">4</div>
<div class="dis_5">5</div>
<div class="dis_3">6</div>
  </body>
      

Run codeHide result


+1


source


You can use Array.from()

a $("[class*='dis_']")

as a parameter, Array.prototype.reduce()

a simple object Map

in the second parameter to set "dis_N"

as a property with the value established in accordance .className

with RegExp

/dis_\d+/

, which is also transmitted to the challenge jQuery()

, concatenated with "."

at .length

chained.

var len = Array.from($("[class*='dis_']"))
          .reduce(function(o, el) {
            var c = el.className.match(/dis_\d+/).pop();
            o[c] = $("." + c).length;
            return o
          }, {});

console.log(len);
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<div class="abc dis_1"></div>
<div class="dis_2 def"></div>
<div class="ghi dis_2"></div>
<div class="dis_3 jkl"></div>
<div class="mno dis_4"></div>
<div class="dis_2 pqr stu v w xy z"></div>
      

Run codeHide result


+1


source


  
$(function(){
  var classes = {};
  $('[class^=dis_]').each(function(index,item){
  var reg = /\s*dis_\w+/g;
  var className = $(item).attr('class');
  var regElements = className.match(reg);
      
  for(var i=0;i<regElements.length;i++){
    var matchClassName = $.trim(regElements[i])
    if(classes.hasOwnProperty(matchClassName)){
      classes[matchClassName] += 1;
        }else{
       classes[matchClassName] = 1;
      }
    }
    })
    console.log(classes)
  })
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="dis_1">Class 1</div>
<div class="dis_1 test">Class 1</div>
<div class="dis_1 dis_5 disable">Class 1</div>
<div class="dis_5 dis_2">Class 5</div>
<div class="dis_5">Class 5</div>
<div class="dis_2">Class 2</div>
<div class="">Class 3</div>
      

Run codeHide result


+1


source


Using JQuery.length will give you back the count of the selected element

-4


source







All Articles