Jitender
Jitender

Reputation: 7971

Each function in jQuery

i have four div in one parent and each contains one image. i want show width of that particular image in respective div. but my function return the last image width in all container.

<head>
  <script type="text/javascript" src="jquery-1.7.2.js"></script>
  <script type="text/javascript">
  $(function () {
    $('.box').each(function () {
      var height = $(this).find('img').height();
      var width = $(this).find('img').width();
      $('.width').text(width)
    })
  })
  </script>
  <style>
  .box {
    float:left;
    margin-left:20px;
    position:relative
  }
  .width {
    position:absolute;
    left:0;
    top:0;
    color:#FFF;
    font-size:20px;
  }
  </style>
</head>
<body>
  <div class="container">
    <div class="box">
      <div class="width"></div>
      <img src="img/sample1.jpg" height="200" width="300" />
    </div>
    <div class="box">
      <div class="width"></div>
      <img src="img/sample2.jpg" height="200" width="350" />
    </div>
    <div class="box">
      <div class="width"></div>
      <img src="img/sample3.jpg" height="200" width="150" />
    </div>
    <div class="box">
      <div class="width"></div>
      <img src="img/sample4.jpg" height="200" width="100" />
    </div>
  </div>
</body>

Upvotes: 3

Views: 2659

Answers (4)

Matt
Matt

Reputation: 3848

$('.width').text(width);  // bad

'.width' is matching all 4 .width elements and then text() is only acting on one of them

you want

$(this).find('.width').text(width);

here we specify we only want the .width element found under (this)

Upvotes: 2

Inkbug
Inkbug

Reputation: 1692

$(this).find('.width').text(width).

Upvotes: 2

CKKiller
CKKiller

Reputation: 1422

use $(this).parent().children('.width') instead of $('.width')

Upvotes: 1

James Allardice
James Allardice

Reputation: 165971

You need to target the .width element that is a child of this, as you've done to find the img element:

$(function (){
    $('.box').each(function (){
        var $this = $(this); //Cache jQuery-wrapped `this` (more efficient)
        var height= $this.find('img').height();
        var width=  $this.find('img').width();
        $this.find('.width').text(width); //Find the descendant `.width` element
    });
}); //You missed these 2 semicolons.

Upvotes: 10

Related Questions