ptamzz
ptamzz

Reputation: 9365

How to assign specific class according to number of elements using jQuery

I've this markup as

<div id="one" class="content">
    <a href="#">a</a>
    <a href="#">b</a>
    <a href="#">c</a>
</div>
<div id="two" class="content">
    <a href="#">d</a>
    <a href="#">e/a>
</div>
<div id="three" class="content">
    <a href="#">f</a>
</div>

Is there a way in which according to the number of a elements in each div.content, I can assign a different class to the div.content element.

For example, in div#one, I've 3 a elements, so I'll do $('div#one').addClass('three-img'); in div#two, I've 2 a elements, so I'll do $('div#two').addClass('two-img') while in div#three, I've only 1 a element, so I'll do $('div#three').addClass('one-img').

The following jQuery codes work for only div#one. What I want is a generic code which will be applied to every div.content in the page (there could be unknown number of div.content elements having either 1 or 2 or 3 a elements inside it.

if($('#one a').length == 3){
    $('#one a').parent().addClass('three-img');
} else if($('#one a').length == 2){
    $('#one a').parent().addClass('two-img');
} else if($('#one a').length == 1){
    $('#one a').parent().addClass('one-img');
}

Upvotes: 1

Views: 197

Answers (5)

adeneo
adeneo

Reputation: 318182

var numbtxt = ['one', 'two', 'three'];

$('.content').each(function(){
    $(this).addClass(numbtxt[$('a', this).length-1]+'-img');
});

Upvotes: 1

Davide
Davide

Reputation: 2339

I would go for something like this:

var classes = { 1: 'one-img', 2: 'two-img', 3: 'three-img' };

$('div.content').each( function() {
  var content = $(this);
  content.addClass( classes[content.children().length] );
});

Check a test here

Upvotes: 1

DG3
DG3

Reputation: 5298

Would this help? You can loop through all the div with the class content and get the current divs children

$(document).ready(function(){
        $("div.content").each(function(e){
            var numberofchildren = $(this).find("a").length;
            if(numberofchildren == 3){
                $(this).addClass("three-img")   
            } 
            else if(numberofchildren == 2){
                $(this).addClass("two-img") 
            }
            else {
                $(this).addClass("one-img")     
            }
        });
    });

Or you can add the class dynamically as below

$(document).ready(function(){
        $("div.content").each(function(e){
            var numberofchildren = $(this).find("a").length;
            $(this).addClass("img-" + numberofchildren);

        });
    });

Upvotes: 1

karim79
karim79

Reputation: 342635

I would do it this way:

$(".content").each(function () {
    $(this).addClass("img_" + $(this).find("a").length);
});

That assumes your classes are named img_1, img_2, etc.

Upvotes: 1

Johan
Johan

Reputation: 35194

$('.content').each(function(i){
    $(this).addClass(i + 'img');
});

Something like that?

Upvotes: 1

Related Questions