0

I've been scouring the web for hours trying to find a solution to this that works for me but I just can't seem to find one.

I need an image ([alt="post-banner"]) to be moved into #blog-banner-container. The problem is, all the images with that alt get moved into the first div. I'm presuming I have to use .closest() but I don't know how to use it.

jQuery

$('[alt="post-banner"]').appendTo('#blog-banner-container');

HTML

    <div class="blog-entry">
        <div id="blog-banner-container"></div>
        <div class="blog-entry-title">Title</div>
        <div class="blog-entry-body">
            <img src="#" alt="post-banner" />
        </div>
    </div>

   <div class="blog-entry">
        <div id="blog-banner-container"></div>
        <div class="blog-entry-title">Title</div>
        <div class="blog-entry-body">
            <img src="#" alt="post-banner" />
        </div>
    </div>

   <div class="blog-entry">
        <div id="blog-banner-container"></div>
        <div class="blog-entry-title">Title</div>
        <div class="blog-entry-body">
            <img src="#" alt="post-banner" />
        </div>
    </div>
4

1 回答 1

0

您可以选择父级,然后选择具有您要查找的 ID 的级别的兄弟级。

jsFiddle

HTML

<div class="blog-entry">
        <div id="blog-banner-container"></div>
        <div class="blog-entry-title">Title</div>
        <div class="blog-entry-body">
            <img src="#" alt="post-banner" />
        </div>
    </div>

   <div class="blog-entry">
        <div id="blog-banner-container"></div>
        <div class="blog-entry-title">Title</div>
        <div class="blog-entry-body">
            <img src="#" alt="post-banner" />
        </div>
    </div>

   <div class="blog-entry">
        <div id="blog-banner-container"></div>
        <div class="blog-entry-title">Title</div>
        <div class="blog-entry-body">
            <img src="#" alt="post-banner" />
        </div>
    </div>

Javascript

$('[alt="post-banner"]').each(function() {
    $(this).parents().siblings('#blog-banner-container').append(this);
});
于 2013-08-11T06:11:14.367 回答