0

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

2
Contributors
4
Replies
12
Views
4 Years
Discussion Span
Last Post by Violet_82
0

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.

0

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

0

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.

0

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

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.