Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Putting javascript id inside div with jQuery

$('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"));
like image 709
bbarnhart Avatar asked Sep 09 '26 13:09

bbarnhart


1 Answers

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>
like image 79
cletus Avatar answered Sep 12 '26 04:09

cletus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!