Question

I'm trying prepend an image to the img-wrapper div and wrap it in the href of the post-title anchor. Maybe that is confusing. Heres the code:

     $(".post").each(function() {
    if($(this).find(".post-excerpt > p:first-child").has("img").length){

        if($(this).find(".post-title").has("a").length){

            $(this).find(".img-wrapper").prepend("<a href='"+$(this).find(".post-title a").attr("href")+"'></a>");

            $(this).find(".post-excerpt > p:first-child").has("img").find("img").prependTo($(this).find(".img-wrapper a"));

        }else{

            $(this).find(".post-excerpt > p:first-child").has("img").find("img").prependTo($(this).find(".img-wrapper"));
        }
    }
});

Everything is working, but the anchor and div are being added in 2 places, the correct place(inside .img-wrapper, and also to .post-title a. I can't understand why its being added to the post-title a. Here is the resulting html:

<article class="post">

    <div class="img-wrapper"><a href="/test-image-post/#top"><img alt="" src="/content/images/2013/Oct/img.jpg"></a>

        <header class="post-header">

            <h2 class="post-title"><a href="/test-image-post/#top"><img alt="" src="/content/images/2013/Oct/img.jpg">Post Title</a></h2>

        </header>

        <section class="post-excerpt">

        </section>

    </div>

</article>

Again, I am trying to prepend the image only to the img-wrapper div. Thanks.

Was it helpful?

Solution

I have tried replicating your code on my local system and found that images were coming twice because of :

".img-wrapper a", instead you have to use it as ".img-wrapper > a:first-child" after prepending anchor.

Fiddle here : http://jsfiddle.net/BvGXs/

Image are not loading due to path, although correctly prepended.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top