Reputation: 868
Get class from div inside an li and add to the same li.
The list items look similar to this:
<li class="original">
<div id="one" class="text">foo</div>
<div id="two" class="photo">foo</div>
<div id="three" class="video">foo</div>
</li>
<li class="original">
<div id="one" class="text">foo2</div>
<div id="two" class="photo">foo2</div>
<div id="three" class="video">foo2</div>
</li>
...
I need to grab the class from each of the list item's divs with an id of "three" and add it to the parent li's class. So, after the code runs the list will look like this:
<li class="original video">
<div id="one" class="text">foo</div>
<div id="two" class="photo">foo</div>
<div id="three" class="video">foo</div>
</li>
<li class="original text">
<div id="one" class="video">foo2</div>
<div id="two" class="photo">foo2</div>
<div id="three" class="text">foo2</div>
</li>
I tried something like this but it only updates the first list item:
$("#three").each(function(i) {
var newclass = $(this).attr("class");
$(this).parent().addClass(newclass);
});
Thanks in advance for your help!
Upvotes: 0
Views: 1848
Reputation: 356
here is another solution you might want to take a look: demo
here is the JS code (After fixing the broken HTML issue people commented above but keeping the duplicate IDs)
$(document).ready(function(){
$('.original').each(function(i) {
var div = $(this).find('div').eq(2);
var newclass = $(div).attr("class");
$(this).addClass(newclass);
});
});
Upvotes: 0
Reputation: 171679
If you are stuck with the repeating ID's
$('[id="three"]').each(function(){
$(this).parent().addClass( this.className);
})
Upvotes: 1
Reputation: 2591
You can't have multiple elements with the same ID. In this case, jquery each is doing the correct thing and finding the first ID then stopping. You can fix this by using the class instead:
<li class="original video"><div class="text one">foo</div></li>
<li><div class="photo two">foo</div></li>
<li><div class="video three">foo</div></li>
<li class="original"><div class="video one">foo2</div></li>
<li><div class="text two">foo2</div></li>
<li><div class="photo three">foo2</div></li>
Then the jquery:
$(".three").each(function(i) {
var newclass = $(this).attr("class");
$(this).parent().addClass(newclass);
});
Upvotes: 0