Yaniv Kossas
Yaniv Kossas

Reputation: 191

Image height will only be retrieved once out of a big array of images

So like i wrote in the title, i have multiple elements with same class i fetch that class and try to check for the child image's width/height/src of that image.

i only manage to get the height // width of the first image however i get the src of all images.

here is the html:

<a class="test">
<img src="http://www.kitchenspro.com/files/Testimonials/Large/1502046700250312a71707.jpg">
</a>
<a class="test">
<img src="http://www.kitchenspro.com/files/Testimonials/Large/40183.9461166782.jpg">
</a>
<a class="test">
<img src="http://sphotos-a.xx.fbcdn.net/hphotos-ash4/s480x480/391362_365319466870994_1543740404_n.jpg">
</a>

here is the jquery

var imagesrc= "";
var imageheight = "";
var imagewidth = "";
var i=0;
$(".test > img").each(function() {
i++;
imagesrc = $(this).attr("src");
imageheight = $(this).width();
imagewidth = $(this).height();
document.write("<br>This is image's src: " + imagesrc + " This is img height: " + imageheight + " this is width: " + imagewidth + "<br>");            
});

I apologize if i didnt present the code the right way.

Any help would be highly appreciated.

Thanks in advanced.

Upvotes: 0

Views: 44

Answers (2)

Alex Grande
Alex Grande

Reputation: 8027

Exactly what @Musa said.

To help clean up your code and give a lesson on efficiency and native javascript, I have supplied a snippet.

// Document Fragments are lightweight DOM containers. Append elements to this in loops and then attach the fragment to the actual DOM afterwards to increase efficiency. 
var frag = document.createDocumentFragment();

// i, or index, comes out of box in most loops.
$(".test img").each(function(i, el) {
 // Local variables specific to each image
 var imagesrc = $(this).attr("src");
 var imageheight = $(this).width();
 var imagewidth = $(this).height();
 var message = "This is image's src: " + imagesrc + " This is img height: " + imageheight + " this is width: " + imagewidth;

 // Appending the node to the frag with native js
 var p = document.createElement("p");
 p.innerText = message;
 frag.appendChild(p);

 // Viewing the console message for fun
 console.log(message);     
});

document.body.appendChild(frag);

Upvotes: 1

Musa
Musa

Reputation: 97672

The first call to document.write destroys the rest of elements so that's why you only get information from one of them, use .append() or something else to show your results.

Upvotes: 2

Related Questions