Search code examples
javascriptjqueryappendclosest

How to append each individual ul with class to the closest article tag above it?


Currently the code is as follows:

<article id="post-529"></article>
<ul class="post-meta"></ul>

<article id="post-530"></article>
<ul class="post-meta"></ul>

<article id="post-531"></article>
<ul class="post-meta"></ul>

I need to have each individual ul with the class of post-meta append to the article right above them. Do you guys have any clues? I used the following function but it just appends all the ul's to all the articles. I'd really appreciate any help. Thanks so much.

$(".post-meta").each(function() {
    $(this).siblings("article").append(this);
});


Solution

  • Use prev() to target the previous sibling

    $(".post-meta").each(function() {
        $(this).prev("article").append(this);
    });