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"));
1
  • Well that was weirde... accepted then unaccepted. Fleeting. :) Commented Feb 8, 2009 at 12:24

2 Answers 2

8

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"></script>
<script>
  google.load("jquery", "1.3.1");
  google.setOnLoadCallback(function() {
    $(function() {
      $("div.box").each(function() {
        $(this).html("ID: " + this.id);
      });
    });
  });
</script>
</body>
</html>
Sign up to request clarification or add additional context in comments.

Comments

5

You'll want to loop through each item.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.