ilyo
ilyo

Reputation: 36421

Storing $(this) in a variable

If I want to save this as a jQuery DOM object and then select it, which method below should I use?

var element = $(this)

And then for selecting

$(element)

Or simply

var element = this

Also, if I want then to concatenate element into a larger selector, is this:

$(element + " .class")

the right way?

Upvotes: 11

Views: 36910

Answers (5)

user7731358
user7731358

Reputation: 19

The right way is:

var element= this.html();
$(element).find(div) /* from modefy div you can change it with any other selector */
$(element).attr({"class":"myClass","other atrribut":"it's value"});

I hope that is useful.

Upvotes: 1

OlliM
OlliM

Reputation: 7113

If you want to select all items with class myClass, you should do:

var $this = $(this);
var myClassElements = $(".myClass", $this);

Upvotes: 2

TheUnexpected
TheUnexpected

Reputation: 3177

var element = $(this) for storing

then element for selecting

Upvotes: 2

gabitzish
gabitzish

Reputation: 9691

var element = $(this)

Then you can use element instead of $(this). You don't have to insert element into $() anymore.

For example : element.remove() instead of $(this).remove()

Upvotes: 20

CambridgeMike
CambridgeMike

Reputation: 4622

$this = $(this) is usually what people do. The dollar sign is a valid character for a variable name, so it serves as a good reminder that the variable is a jQuery object.

You can then use $this as you would any jQuery element. For example, $this.css('border', 'none')

Upvotes: 12

Related Questions