Xarcell
Xarcell

Reputation: 2011

jQuery: Detect Number Of Elements, Then Apply Class

I'm working on a responsive theme and I don't have any idea how many widgets a person might add to there site within the footer section via admin. So I'm trying to use jQuery to detect how many div.widget there are, and add a class to the parent div on how many are found. So I can adjust the width. I won't pretend that I understand jQuery, I don't, but I try. I'm also open to other suggestions on how to handle this.

Anyway, I can't get the following below to work...

HTML:

<div id="main-footer-section">
    <div class="widget">Widget One</div>
    <div class="widget">Widget Two</div>
</div>

CSS:

.widget { background: #ccc; color: #fff; font: 1em sans-serif; margin: 5px; padding: 5%; text-align: center; }

#main-footer-section.widget-count-2 .widget {
    width: 50%;
}
#main-footer-section.widget-count-3 .widget {
    width: 33%;
}
#main-footer-section.widget-count-4 .widget {
    width: 25%;
}

jQuery:

$('#main-footer-section').each(function() 
    {
        if $(this).children('.widget').length = 2) {
            $(this).find('#main-footer-section').addClass('widget-count-2');
            }
        if $(this).children('.widget').length = 3) {
            $(this).find('#main-footer-section').addClass('widget-count-3');
            }
        if $(this).children('.widget').length = 4) {
            $(this).find('#main-footer-section').addClass('widget-count-4');
            }
    });

http://jsfiddle.net/epwmzrkb/1/

Upvotes: 0

Views: 57

Answers (2)

max
max

Reputation: 102001

$(function(){
    var $main = $("#main-footer-section").addClass( function(){
      return "widget-count-" + $(this).children('.widget').length;
    });
});

http://jsfiddle.net/maxcal/86hsajd8/2/

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

The main issue in your script is there is syntactical errors, also #main-footer-section is not a descendant of this, it is the this element so $(this).find('#main-footer-section') won't return anything

$('#main-footer-section').addClass(function(i, clazz) {
  var len = $(this).children('.widget').length;
  return len > 1 && len < 5 ? 'widget-count-' + len : '';
});
.widget {
  background: #ccc;
  color: #fff;
  font: 1em sans-serif;
  margin: 5px;
  padding: 5%;
  text-align: center;
}
#main-footer-section.widget-count-2 .widget {
  /*this will not work because of the margin given to .widget*/
  width: 50%;
  color: red;
}
#main-footer-section.widget-count-3 .widget {
  width: 33%;
  color: green;
}
#main-footer-section.widget-count-4 .widget {
  width: 25%;
  color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="main-footer-section" class="x">
  <div class="widget">Widget One</div>
  <div class="widget">Widget Two</div>
</div>

Upvotes: 3

Related Questions