Zach Nicodemous
Zach Nicodemous

Reputation: 9487

jQuery move/append multiple items with same class name, inside parent div only

I have a dynamically generated page with the following structure:

<div class="list-item">
    <div class="year">xxx1</div>
    <div class="other-data">xxx1</div>
    <div class="item-title">Title 1</div>
    <div class="item-information"></div>
</div>
<div class="list-item">
    <div class="year">xxx2</div>
    <div class="other-data">xxx2</div>
    <div class="item-title">Title 2</div>
    <div class="item-information"></div>
</div>

There are multiple list items on the page.

Within each list-item, I need to take "year" and "other-data" and remove it from above the item-title and appendTo "item-information".

I have tried the following:

$('.year').appendTo('.item-information');
$('.other-data').appendTo('.item-information');

This does not work properly, as it basically takes ALL instances of "year" and appends it to "item-information" - so if there are 3 items on the page, each item ends up showing 3 instances of "year" in each "item-information".

In order to resolve this, I know I need some kind of statement that selects the list-item, finds year and other-data within that list item, then finds item-information within the same list item and appends it there.

The problem is, I am not sure how to structure the statement, I tried the below but it errored out:

$('.list-item').find('.year').appendTo(function({
    $(this).find('.item-information');
});

Could someone help me out with the correct structure for what I want to do?

Thanks.

Upvotes: 2

Views: 5978

Answers (2)

PeterKA
PeterKA

Reputation: 24638

You can use append(function) and .siblings() as follows:

$('.item-information').append(function() {  
    return $(this).siblings('.year,.other-data');
});

   $('.item-information').append(function() {  
        return $(this).siblings('.year,.other-data');
    });

//output new html
$('pre.out').text( $('<div/>').html( $('div.list-item').clone() ).html() );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="list-item">
    <div class="year">xxx1</div>
    <div class="other-data">xxx1</div>
    <div class="item-title">Title 1</div>
    <div class="item-information"></div>
</div>
<div class="list-item">
    <div class="year">xxx2</div>
    <div class="other-data">xxx2</div>
    <div class="item-title">Title 2</div>
    <div class="item-information"></div>
</div>

<h1>NEW HTML</h1>
<pre class="out"></pre>

Upvotes: 0

errand
errand

Reputation: 980

$(".list-item").each(function () {    //loop over each list item
    myYear= $(".year", this);         //get the year of the current list item
    $(".item-information", this).append(myYear); //append it to the item information
});

you could do this, then of course for every other list item child element ;)

Upvotes: 3

Related Questions