travis_arnold
travis_arnold

Reputation: 77

Add child data attribute name and value to parent for each

I have looped divs that contain a child element with a data attribute named data-rating. What I need to do is grab the child's attribute and value and add to the parent div for each.

Here is the code:

<div class="tile">                                      
    <div class="title-band">
        <h3>Test Agency</h3>
        <ul data-rating="3.0" class="rating" data-id="13">
            <li class="whole"><span class="l"></span><span class="r"></span></li>
        </ul>                   
    </div>
</div>

<div class="tile">                                      
    <div class="title-band">
        <h3>Another Agency</h3>
        <ul data-rating="2.0" class="rating" data-id="14">
            <li class="whole"><span class="l"></span><span class="r"></span></li>
        </ul>                   
    </div>
</div>

Here's what I'd like to accomplish:

<div class="tile" data-rating="3.0">                                        
    <div class="title-band">
        <h3>Test Agency</h3>
        <ul data-rating="3.0" class="rating" data-id="13">
            <li class="whole"><span class="l"></span><span class="r"></span></li>
        </ul>                   
    </div>
</div>

<div class="tile" data-rating="2.0">                                        
    <div class="title-band">
        <h3>Test Agency</h3>
        <ul data-rating="2.0" class="rating" data-id="14">
            <li class="whole"><span class="l"></span><span class="r"></span></li>
        </ul>                   
    </div>
</div>

Any help is appreciated.

Upvotes: 1

Views: 2867

Answers (3)

Mark Eriksson
Mark Eriksson

Reputation: 1475

$('ul[data-rating]').each(function(i,a) {
    $(a).parent().attr('data-rating', $(a).data('rating'));
});

Upvotes: 1

Shay
Shay

Reputation: 1778

div with a child element that has data-rating attribute:

$('div > [data-rating]').each(function(){
    $(this).parent().attr('data-rating', $(this).data('rating'));
});

if the child element is not the first level, remove the >.

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

You can fetch the parent div using its class title-band then use .attr() to set the attribute value like

Try

jQuery(function ($) {
    $('.title-band').attr('data-rating', function () {
        return $(this).find('ul').data('rating')
    })
})

Demo: Fiddle

Upvotes: 1

Related Questions