Chaps,
I was wondering what this.id (and for that matter this.whatever) is in jquery and how to use it. A few quick examples are here:

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>

<img title="hat.gif"/>

<script>
$("img").attr("src", function() {
    return "/resources/" + this.title;
});
</script>

</body>
</html>

and another one:

<!DOCTYPE html>
<html>
<head>
  <style>
  div { color:blue; }
  span { color:red; }
  b { font-weight:bolder; }
        </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>

  <div>Zero-th <span></span></div>
  <div>First <span></span></div>
  <div>Second <span></span></div>

<script>
$("div").attr("id", function (arr) {
  return "div-id" + arr;
})
.each(function () {
  $("span", this).html("(ID = '<b>" + this.id + "</b>')");
});
</script>

</body>
</html>

thanks

Recommended Answers

All 4 Replies

this points to the current dom element. For example if you do:

$('p').each(function(){
    alert(this.id);
});

It loops over every paragraph, and within each loop this is the paragraph which is the current one in that loop. The alert will show the paragraph's id attribute.

thanks, that's much clearer now, so can this be used with anything then or just ids? Like the above example shows id.title, so can I use this.anyHTMLtag, this.class, etc or is there some kind of rule that limits its usage? I had a look around on the net but to be honest with you I didn't find anything that helpful or easy to understand
thanks

Since this is basically a dom element, you should be able to use all attributes (id, class, name, style, href, etc.) of a tag.

If you put this in a var, you should be able to inspect it, and see what it contains.

ah ok so it takes just attributes and not tags, ok thanks for this (no pun intended!)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.