Florin Simion Florin Simion - 5 months ago 11
jQuery Question

jQuery get content of a div and make it a class of its parent element

How can I get the content of

.getClass
(white, blue etc) and add it as a class for its parent li tag?

I have the following html structure:

<div class="main">
<ul>
<li class="even">
<div class="content">
<div class="getClass">white</div>
</div>
</li>
<li class="odd">
<div class="content">
<div class="getClass">red</div>
</div>
</li>
<li class="even">
<div class="content">
<div class="getClass">blue</div>
</div>
</li>
<li class="odd">
<div class="content">
<div class="getClass">black</div>
</div>
</li>
</ul>
</div>


I've come up with this:

var str = $( ".getClass" ).text();


What's next?

Cheers

Answer

Select the elements you want to modify, use .each to create a loop, then use .text() to get the content of each element:

$('li').each(function (i, el) {
    var className = $(el).find('#getClass').text();
    $(el).addClass(className)
});

But your code is actually invalid HTML, you have duplicate id attributes. So use classes instead, you almost never need id

Comments