Wojciech Maj
Wojciech Maj

Reputation: 1122

Child of array element

I had a div with class cover_container and img inside it. The code used to get img height and apply it to its parent div. Here's what I did.

$('.cover_container').height($(".cover_container img").height());

Easy stuff. However, now I have multiple cover_containers on one page and I started to struggle. Here's what I did:

for($a = 0; $a < $('.cover_container').length; $a++) {
  $currentcovercontainer = $('.cover_container')[$a];
  $currentcovercontainer.height($currentcovercontainer.children('img')[0].height());
}

This, however, gives me the following error:

[21:33:57.440] TypeError: $currentcovercontainer.children is not a function

I've also tried ideas like jQuery($currentcovercontainer).find('img')[0].height() or $currentcovercontainer.height($('> img').height() however with no success.

Any ideas on what am I doing wrong?

Thanks a lot in advance!

Upvotes: 1

Views: 69

Answers (3)

Matt
Matt

Reputation: 75327

$('.cover_container')[$a] gives you a DOM Element, not a jQuery object;

for(var $a = 0; $a < $('.cover_container').length; $a++) {
  var $currentcovercontainer = $($('.cover_container')[$a]);
  $currentcovercontainer.height($($currentcovercontainer.children('img')[0]).height());
}

... although eq() works like [], but returns a jQuery object for you;

for(var $a = 0; $a < $('.cover_container').length; $a++) {
  var $currentcovercontainer = $('.cover_container').get($a);
  $currentcovercontainer.height($currentcovercontainer.children('img').height());
}

Although this could be more jQuery-esque using each;

$('.cover_container').each(function () {
    var $this = $(this);

    $this.height($this.children('img').height());
});

Also note that the $a syntax is usually used to denote a jQuery object; $a will be a number, not a jQuery object. Don't forget to declare your variables using var as well :).

Upvotes: 1

BrunoLM
BrunoLM

Reputation: 100371

You can use .each function to execute a function 1 by 1

$('.cover_container').each(function() {
    var $this = $(this);
    $this.height($this.find("img").height());
});

See this example on jsFiddle

Upvotes: 2

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324760

I'll write this in Vanilla JS - you can either keep it as is or convert it to jQuery if you must:

var qsa = document.querySelectorAll(".cover_container"),
    l = qsa.length, i;
// note: querySelectorAll is more widely supported than getElementsByClassName
for( i=0; i<l; i++) {
    qsa[i].style.height = qsa[i].querySelector("img").height+"px";
}

It can be made simpler if your HTML is regular, such as <div class="cover_container"><img src="..." /></div>, because then you can use qsa[i].children[0].height

Upvotes: 2

Related Questions