3

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>
1

4 Answers 4

10

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.
Sign up to request clarification or add additional context in comments.

4 Comments

This code is correct. You were giving width to each div(width class) instead of current div. $(this).find('.width').text(width) will only set the set to current div not all four.
can i also get box number with width
@james: like i have four box. i want to get box. first box should have text 1, second 2 etc
@amit - You can use $this.index() to get the index of the element relative to its siblings.
2

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

Comments

2
$('.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)

Comments

1

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

2 Comments

This will still set the text of all .width elements (since $(this).parent() will return div.container).
He's changed it since I answered, was multiple div.containers.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.