Cláudio Barreira
Cláudio Barreira

Reputation: 459

Add specific class to child from parent

I got some list items with a child element. What I want is that each child of the li get a class based on their parents id class. But all the elements are getting the id of the first li.

HTML

<ul>
  <li class="test post-91 other">
    <a class='link'></a> 
  </li>
  <li class="test post-43 other">
    <a class='link'></a>
  </li>  
</ul>

JQUERY

var id = $('.link').closest('li').attr("class").split(' ')[1];
id = id.replace(/[^0-9]/g, '');
id = "class-"+id;
$('.link').addClass(id);

I want the elements to get the number of the "post-" from their parent li.

https://jsfiddle.net/f5Lqzzew/

Upvotes: 2

Views: 88

Answers (3)

Mahesh Jasti
Mahesh Jasti

Reputation: 572

Update the script to do a loop on all li's. This is working...

<script>
$('ul li').prepend("<a class='link'></a>");

$('li').each(function(i,v){
  var v = $(this)[0].className;
  v = v.split(' ')[1];

    v = v.replace(/[^0-9]/g, '');
    v = "class-"+v;
  $(this).children('a.link').addClass(v);
  $(this).children('a.link').text(v);
});

</script>

Upvotes: 1

Vivek Tankaria
Vivek Tankaria

Reputation: 1311

One more Solution : Here all li can be taken in loop and then find the anchor inside it and assign the class to it.

$("ul li").each(function(){
    var id = $(this).attr('class').split(' ')[1].replace(/[^0-9]/g, '');
    $(this).find("a.link").text('class-' + id).addClass("class-"+id); // demo purposes only
});

Updated Fiddle

Upvotes: 2

Rory McCrossan
Rory McCrossan

Reputation: 337570

You need to calculate the class based on the specific li element itself. To do this, you can pass a function to the addClass() method. Try this:

$('.link').addClass(function() {
    var id = $(this).closest('li').attr('class').split(' ')[1].replace(/[^0-9]/g, '');
    return 'class-' + id;
});

Updated fiddle

Upvotes: 2

Related Questions