1

If I had a jQuery object and wanted to call itself, is there any better way of doing that then like…

$("#notes").text($("#notes").data("defaulttext"));

I mean… I know I can do something like

var $notes = $("#notes");

to speed up things a bit, but I was just wondering if there is any variable I could use that means "the object I am currently working on", instead of manually typing in the object name again.

3
  • 2nd way is correct ,use reference to Dom element Commented Mar 31, 2014 at 5:29
  • use $(this) for current object Commented Mar 31, 2014 at 5:29
  • The $(this) method doesn't work. I actually tried that before posting my question. I was hoping for something that simple, though. Commented Mar 31, 2014 at 5:37

1 Answer 1

5

Pass a function inside .text() method and in that function return your object's data attribute using this object

$("#notes").text(function(){
    return $(this).data("defaulttext")
    });

Or in order to be less ugly you can create a plugin using

$.fn.edit = function() {
this.text(this.data('defaulttext'));
return this;   //to maintain chainability
};

and then use like

 $("css_Selector").edit();

to change the text of element to its data-defaulttext attribute

Sign up to request clarification or add additional context in comments.

6 Comments

How about this?: $("#notes").text($(this).data("defaulttext")); will this refer to #notes?
Yes that one too added see the changes,Thanks
The latter $(this) method doesn't work. I actually tried that before posting my question. I was hoping for something that simple.
Well you can use the first one then
Yeah, it just gets pretty ugly when I put together a big chain of methods doing the first one. Thanks, though.
|

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.