Skip to content Skip to sidebar Skip to footer

Can I Use $(this) As A Javascript Variable?

I'm writing a function which requires knowing the location of the clicked div. I'm wondering if I can get the location of a clicked object as a javascript variable? here is the co

Solution 1:

this refers to the current element.

In jQuery, as they use $() to get an element, $(this) returns the jQuery equivalent of vanilla JS's this.

<areashape="rect"coords="103, 0, 213, 25"href="#"onClick="swap3(this,'product-details','product-specs');">

Solution 2:

$() returns a DOM element (like an object that you can work with it's methods, properties, etc) and if you set a variable to it, the variable must work like an jQuery-Object correctly. But in my experience, some times that DO NOT! and I learn the best way is to get the variable by jQuery-selector ($). Your code is correct, but should be better if you apply these changes:

functionswap3(currentDivId ,oldDivId, newDivId) {
    var oldDiv = $(currentDivId).nextAll("div." + oldDivId);
    var newDiv = $(currentDivId).nextAll("div." + newDivId);
    $(oldDiv).css({"display" : "none"});
    $(newDiv).css({"display" : "block"});
}

Post a Comment for "Can I Use $(this) As A Javascript Variable?"