views:

605

answers:

2
$('div.box').html("hello")

puts the word hello inside all my div's of class 'box'. They all have an assigned id.

I'm trying to figure out how to put each div's id instead of 'hello' inside the div. Maybe this is really easy, but I can't figure it out. I'm also new to jQuery. Any ideas? I've tried:

$("div.box").html("id: " + $(this).attr("id"));
+8  A: 

Try this:

$("div.box").each(function() {
  $(this).html("Id: " + this.id);
});

Full example:

<html>
<head>
  <title>Layout</title>
</head>
<body>
  <div id="id1" class="box">Box One</div>
  <div id="id2" class="box">Box Two</div>
  <div id="id3">Box Three</div>
  <div id="id4" class="box">Box Four</div>
<script src="http://www.google.com/jsapi"&gt;&lt;/script&gt;
<script>
  google.load("jquery", "1.3.1");
  google.setOnLoadCallback(function() {
    $(function() {
      $("div.box").each(function() {
        $(this).html("ID: " + this.id);
      });
    });
  });
</script>
</body>
</html>
cletus
Perfect. Thanks.
bbarnhart
+1 i've never seen the JSAPI before very cool.
bendewey
+5  A: 

You'll want to loop through each item.

$("div.box").each(function()
{
  $(this).html("id: " + this.id);
});
bendewey