James Beardmore
James Beardmore

Reputation: 3

Apply all child classes to parent elements

I currently have the following markup:

<div class="foo">
  <ul class="bar">
    <li class="a"></li>
    <li class="b"></li>
  </ul>
</div>

<div class="foo">
  <ul class="bar">
    <li class="c"></li>
    <li class="d"></li>
  </ul>
</div>

And I need to and up with the following, by getting all classes form the child li and applying them to only that specific .foo:

<div class="foo a b">
  <ul class="bar">
    <li class="a"></li>
    <li class="b"></li>
  </ul>
</div>

<div class="foo c d">
  <ul class="bar">
    <li class="c"></li>
    <li class="d"></li>
  </ul>
</div>

So far I have the following, but it's only at the stage of getting the first li class and it applies it to all .foo divs as opposed to each specific one.

$(".foo").addClass($('.bar li').attr('class'));

Any pointers in the right direction are very welcome.

Upvotes: 0

Views: 105

Answers (3)

thecodeparadox
thecodeparadox

Reputation: 87073

  $('.foo').addClass(function() {
    var cls = '';
    $('li', this).each(function() {
        cls += this.className.concat(' ');
    });
    return cls;
  });

DEMO

Upvotes: 0

jeffery_the_wind
jeffery_the_wind

Reputation: 18188

Here is some code that does what you need to do:

$('.foo').each(function(i, elem) {
    get_child_classes(this,elem);
});

//the function you need
function get_child_classes (parent,current){
    $(current).each(function(i, elem) {
        $(elem).children().each(function(j, elem1){
            $(parent).addClass($(elem1).attr('class'));
            get_child_classes (parent, elem1);
        });
    });
}

see the fiddle here: http://jsfiddle.net/Zpx8R/ ​ This code should work for all elements, no matter what type of HTML element it is.

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816394

You need to iterate over the .foo elements and then get the class of each of their respective descendants:

$('.foo').each(function() {
    $(this).addClass($(this).find('.bar li').map(function() {
        return this.className;
    }).get().join(' '));
});

Reference: each, map, get

An other, though slower method, because of the .foo lookup, would be:

$('.bar li').each(function() {
    $(this).closest('.foo').addClass(this.className);
});

Reference: closest

Upvotes: 3

Related Questions