Catch the url of the first image of each post (div), store that url in a variable

2

I have a blog, and for each post a div is automatically created. On the home page you should only see the first image of the post and the title (with link) referring to the post. But here, I'd like the image to be set to background-image of its parent div.

To do this, I use a blogger tag that returns the unique id for that post, generated by the blogger himself.

With the id of the div, I use the :first-child selector to get the first image, and successively its url, storing it in a variable, and then use it in the definition of css background-image . As shown in the code:

$(window).load(
    $(function pegaId(id){
            var idDoPost = $("#"+id).attr("id");
                console.log(idDoPost);

            var imagemUrl = document.querySelector("#" + idDoPost + " img").src;
            console.log(imagemUrl);

            $(".post-outer").css("background-image", "url("+imagemUrl+")");

            pegaId("ident<data:post.id/>"); /*chama a função pegaId e passa como parametro o id
                                            que será utilizado para identificar a div*/

}));

The problem is that I have already changed the code several times, I used other selectors, added more functions, changed the position code on the page and nothing.

I search for solutions but I can not find them.

In the console says that the url of the images are "undefined", I think it is because the images are only uploaded later, even using $(document).ready() or $(window).load() .

I wanted someone to help me, because I want to make a code that will take these images automatically.

    
asked by anonymous 06.02.2015 / 14:23

2 answers

1

Assuming that each div of a post has the class "post":

$(function() {
    var urlsImagens = $(".post img:nth-child(1)").map(function() {
       return this.getAttribute("src");
    });
});
    
09.02.2015 / 19:49
0
$(window).load(
    $(function pegaId(id){

            var imagemUrl = document.querySelector(".post-body img:nth-child(1)").src;
            console.log(imagemUrl);

            $("body").css("background-image", "url("+imagemUrl+")");

}));
    
31.03.2016 / 03:04