What does $($(this)) mean? - javascript

I saw some code around the web that uses the following statement
if ($($(this)).hasClass("footer_default")) {
$('#abc')
.appendTo($(this))
.toolbar({position: "fixed"});
}
What is the use of $($(this)) and why is that necessary here?

Yes, $($(this)) is the same as $(this), the jQuery() or $() function is wonderfully idempotent. There is no reason for that particular construction (double wrapping of this), however, something I use as a shortcut for grabbing the first element only from a group, which involves similar double wrapping, is
$($('selector')[0])
Which amounts to, grab every element that matches selector, (which returns a jQuery object), then use [0] to grab the first one on the list (which returns a DOM object), then wrap it in $() again to turn it back into a jQuery object, which this time only contains a single element instead of a collection. It is roughly equivalent to
document.querySelectorAll('selector')[0];, which is pretty much
document.querySelector('selector');

You can wrap $ as many times as you want, it won't change anything.
If foo is a DOM element, $(foo) will return the corresponding jQuery object.
If foo is a jQuery object, $(foo) will return the same object.
That's why $($(this)) will return exactly the same as $(this).

There is no specific need for double-wrapping and $($(this)) is exactly the same as $(this).
That said, I once found this double-wrapping in one file in my project, committed by another developer. Tracking the changes through revision, turned out that it started as $($(this).find('selector').first()) - that is, the result of some selector was wrapped to create a new object. Then for whatever reasons, the selector was removed and only the double-wrapping of this remained. Needless to say, on the next commit it was changed to $(this).

As explained before me, $($(this)) and $(this) are absolutely identical. jQuery returns the same jQuery object if you try to wrap it more than once.
Additionally, for performance considerations it is a good practice to reuse jQuery objects - it is quite expensive to create jQuery objects, especially the ones with complex selectors. Example:
var $this = $(this);
if ($this.hasClass("footer_default")) {
$('#abc')
.appendTo($this)
.toolbar({position: "fixed"});
}
Just google for 'jQuery best practices' - it will take a 30 min for you to learn these basics and you will use jQuery way more effectively.

There is no meainig of doing that.
The following code return the same:
console.log($($(this)).hasClass("footer_default"))
console.log($(this).hasClass("footer_default"))
a boolean value depenging on if the selected element has or not the class footer_default:
.hasClass( className )Returns: Boolean
Demo: http://jsfiddle.net/IrvinDominin/aSzFn/

$(this) and $($(this)) both return jquery object.
There is no difference between these two.

Related

Javascript/jQuery variable, what is the proper way to use a var?

I am sorry if this is a dumb or easy question but I am fairly new to Javascript/jQuery. The past month I have really started to delve into the land of scripting and have seen two different, maybe three, ways people use var in Javascript/jQuery.
The way I use a var is like so,
var nav = $('nav');
nav.hide();
A very common way I have seen people use vars,
var nav = $('nav');
$(nav).hide();
From the answers,
var $nav = $('nav');
$nav.hide();
From what I have learned from searching through Google is what you typed inside the variable is saved there to later be used. I then figured if I wrote the $() around the var when I was using it, it would duplicate the $(). Yet both ways seem to work so I know it does not duplicate it and therefore can tell that it is the same thing.
Is there a correct way to use vars or are both equally the same and it doesn't matter?
I apologize again if this is a known answer and will be happy to remove it if someone can show me the original question but I couldn't find anything on it.
A great bit of information from an answer that I didn't mark as the answer but I find to be very important.
var element = document.createElement("div");
$("body").append(element);
$(element).hide();
In the example above, $(element) is necessary, because it takes a DOM
object and converts it to a jQuery selector. jQuery functions only
work on jQuery selectors, so you couldn't simply do element.hide().
$() creates a new jQuery object. If you save a jQuery object to a variable it is pointless to create another jQuery object from it, although it still works. You will often see people wrap variables that were previously created as jQuery objects in $() purely due to bad practice and either forgetting it's already an object...or not understanding what they just created in the first place
Perhaps you may have seen
var $nav = $('nav');
$nav.hide();
Using the $ prefix is a common practice to denote that the variable is a jQuery object for code readability mostly
Both variables store a jQuery object, which has access to jQuery methods. The latter approach unnecessarily tries to re-wrap that jQuery object in another jQuery object. The former approach is 'correct,' in that it's more efficient and less, to be frank, silly.
I've seen this issue in a lot of places. People use a lot of $ when they don't need to. Some use it just as an ornament on their variable name, which adds to the confusion.
First of all, there are no jQuery variables, only JavaScript variables, and as you said, variables store information. When the right hand side begins with $(), you're storing the results of a jQuery function in the variable. In the vast majority of cases, what you'll be storing is called a jQuery selector.
In the case of var nav = $('nav'), what you're storing is a selector representing all the elements in the DOM that are nav tags, i.e. that look like <nav></nav> (or equivalent).
As others already mentioned, the $(nav) is taking the stored selector, and creating a new selector out of it. It accomplishes nothing and is redundant, and is a poor programming practice, even if it is a pervasive one.
However, there is a similar syntax that makes sense:
var element = document.createElement("div");
$("body").append(element);
$(element).hide();
In the example above, $(element) is necessary, because it takes a DOM object and converts it to a jQuery selector. jQuery functions only work on jQuery selectors, so you couldn't simply do element.hide().
As I mentioned at the top, some people also use $ as a decorator on their variable names, e.g. var $selector = $("nav"). The $ on the left hand side means nothing - it's just a character in a variable name, but they use it as a convention to remind themselves that they're storing a jQuery selector. I'd avoid it, simply because it adds to the confusion, but it's out there, so I just wanted to mention it.
var is used to create any kind of variable. Could be var diceRoll = 4 or var myMessage = "Hello!", or anything else.
$ is a function that jQuery provides, which behaves in different ways depending on what you pass to it. For example, if you pass it a string (e.g. 'nav'), it will find every nav element in the document and return a set of jQuery objects (elements) - one for each DOM element it finds. When you say var nav = $('nav');, you are assigning this set of jQuery objects to your nav variable, so you can work with it later. So far so good.
Instead of passing a string to $, you technically could pass jQuery objects back into the $ function, which is what you are doing when you say $(nav).hide();. DOING THIS MAKES LITTLE SENSE - it will just return the same array of jQuery objects, nav, which you put into it in the first place!!
Personally, I like to prefix any variable which holds a jQuery object with a $ sign, i.e. var $nav = $('nav');. This is just a convention that allows me to see at a glance that this variable holds a jQuery object (element) rather than a native DOM element, or integer, or so on. If I ever see $($myVar) in my code, I know it's probably time for bed...
Update: there are other things that it DOES make sense to pass into the $() function, apart from strings. Passing in a DOM element, for example (such as saying $(document)) creates a jQuery object representation of that DOM element, which can be very useful.
All of these answers are pieces to the entire answer . . . let me add yet another piece. :)
As others have said, the $(...) notation is a JQuery function that returns a JQuery object. Depending on what "..." is, determines how that is done.
Some examples:
if you put a selector, such as "div", in there, you will get a JQuery object that contains all of the DOM elements that match the selector pattern . . . in this case, all of the <div> elements.
if you pass a string representation of an HTML element (e.g., "<div></div>"), you will get a JQuery object that points to a newly created <div> element.
if you put a DOM node reference in there (e.g., one created by using document.getElementsByTagName("div")), it will create a JQuery object that points to that node(s) in the reference.
The whole point of this is that JQuery works with JQuery objects, so these various functions help programmers create them.
Now this is where we get to your question . . .
Each time you use $("..."), you are creating a brand new object, so, for example the following code will produce two unique JQuery objects, each of which pointing to the identical DOM elements:
var $firstObject = $("div");
var $secondObject = $("div");
So, if you do a comparison of them (like this ($firstObject === $secondObject)), they will not be seen as equal, because they are not the same object.
Now, let me do a slight variation of your second example to add a little more clarity. If you create a third variable and set it equal to the second one, like this:
var $thirdObject = $secondObject;
. . . you have two elements that are actually pointing to the same JQuery object, so they ARE actually equal (i.e., ($secondObject === $thirdObject) will evaluate as true).
Now finally, what you've shown with this peice of code:
$(nav).hide();
. . . is simply another example of trying to create a JQuery object . . . this time using another JQuery object. Doing this with that third variable that I created above, however, will now break the relationship that it has with the second variable . . . ($secondObject === $($thirdObject)) . . . they are no longer equal, because the two sides of the comparison no longer point to the same object. Much like the comparison between $firstObject and $secondObject from earlier, that comparison is using two unique JQuery objects.
However . . .
Unlike some of the other answers, I would disagree that it is a completely incorrect form of coding . . . while I would never use it in the situation that you provide in your example, passing a JQuery object into the $(...) function is essentially the same thing as using .clone(). The two $bar assignments below are functionally equivalent:
var $foo = $("<div></div>");
var $bar = $($foo);
var $bar = $foo.clone();
The JQuery API even makes the same point (http://api.jquery.com/jQuery/):
Cloning jQuery Objects
When a jQuery object is passed to the $() function, a clone of the object is created. This new jQuery object references the same DOM elements as the initial one.
EDIT :
Out of curiosity, I set up a quick test at jsPerf and the $($foo) approach is pretty significantly faster than .clone() in Firefox, IE9, and Chrome: http://jsperf.com/clone-technique-test
var nav = $('nav');
$(nav).hide();
nav is already a jQuery object so $(nav) is useless.

Can JQuery and Javascript be mixed together?

I am wondering if I could use query and javascript together so I could select an element by class with the javascript and then use javascript to work on that element. Sorry if that didn't make sense. Here is an example:
$('.nav_flag').src = "images/flags/"+userCountryLower+".gif";
Would that work, if not how do I get an element by class using regular javascript. Thanks!
EDIT:I know JQUERY is JavaScript but I was wondering if I could mix jquery selectors and javascript 'controller'-for a loss of a better word
To answer your question as asked, there are several ways to take a jQuery object, i.e., what is returned by $('some selector'), and get a reference to the underlying DOM element(s).
You can access the individual DOM elements like array elements:
// update the src of the first matching element:
$(".nav_flag")[0].src = "images/flags/"+userCountryLower+".gif";
// if you're going to access more than one you should cache the jQuery object in
// a variable, not keep selecting the same thing via the $() function:
var navFlgEls = $(".nav_flag");
for (var i = 0; i < navFlgEls.length; i++) { ... }
But you wouldn't manually loop through the elements when you can use jQuery's .each() method, noting that within the callback function you provide this will be set to the current DOM element:
$(".nav_flag").each(function() {
this.src = "images/flags/"+userCountryLower+".gif";
});
However, jQuery provides a way to set attributes with one line of code:
$(".nav_flag").attr("src", "images/flags/"+userCountryLower+".gif");
To answer the second part of your question, doing the same thing without jQuery, you can use .getElementsByClassname() or .querySelectorAll() if you don't care about supporting older browsers.
jQuery IS Javascript. You can mix and match them together. But you better know what you're doing.
In this case, you probably want to use .attr function to set value of attribute.
Use .attr() in jQuery, rather than mix the two here.
$('.nav_flag').attr('src', "images/flags/"+userCountryLower+".gif");
In many instances, it is fine to mix jQuery with plain JavaScript, but if you have already included the jQuery library, you might as well make use of it. Unless, that is, you have an operation which in jQuery would be more computationally expensive than the same operation in plain JavaScript.
You can do it with jQuery too:
$('.nav_flag').attr("src", "images/flags/"+userCountryLower+".gif");
keep in mind that jQuery is simply a library built upon javascript.
for any jQuery object, selecting its elements by subscription will return the corresponding dom element.
e.g.
$('#foo')[0] // is equivalent to document.getElementById('foo');
You need to add an index to the jQuery object to get the native Javascript object. Change:
$('.nav_flag').src = "images/flags/"+userCountryLower+".gif";
To:
$('.nav_flag')[0].src = "images/flags/"+userCountryLower+".gif";
To get elements by class name in Javascript you can use:
document.getElementsByClassName( 'nav_flag' )[0].src = "images/flags/"+userCountryLower+".gif";
To answer your question, you could use .toArray() to convert the jQuery object into an array of standard DOM elements. Then either get the first element or loop through the array to set all the elements with the class.
However, you could do this easier with pure jquery with attr or prop depending on the version:
$('.nav_flag').attr("src", "images/flags/"+userCountryLower+".gif");
Or use pure javascript:
if (navFlagElements = document.getElementsByClassName("nav_flag") && navFlagElements.length > 0) {
navFlagElements[0].src = "images/flags/"+userCountryLower+".gif"
}

Difference between $('div div') and $('div').find('div')?

I was just poking around with jQuery, and I stumbled upon the Find function.
I tested like this:
$(document).ready(function(){
$('button').click(function(){
$('div').find('div').fadeOut(2000);
});
});
And this
$(document).ready(function(){
$('button').click(function(){
$('div div').fadeOut(2000);
});
});
And both produce the exact same result.
Whats the difference? :)
In your example there is no difference but there are cases that you can not use the first one, for example let't say you have an element as the parameter of a function and you want to find divs inside it, then you have to use the "Find" method.
function foo(index, el)
{
$(el).find("div")...
}
But when you know the exact path, obviously the second approach is more robus.
There is no difference.
If you already have a jQuery object, the find method is useful.
Otherwise, a single selector is simpler.
Most selectors have method equivalents (.children(), .first(), .not()) for this reason.
The method versions also allow you to call .end() to go back to the previous object.
They both do exactly the same thing, but in older browsers where document.querySelectorAll() is not available (Old IEs) $("div").find("div"); is quicker, as Paul Irish confirms in this comment here.
Another thing to note is that in jQuery you can also do this:
$("div", "#some-element")
Which would search for div inside of #some-element. jQuery actually converts this into:
$("#some-element").find("div")
So it's always suggested to use .find() rather than pass in a context.
In this specific case, they do the same thing. Note that find() will traverse all the descendants of the matched elements.

jquery newbie: how to efficiently do multiple actions on same DOM element?

I recently learned (here on stackoverflow : ) ) that when using jquery every time I write
$("...")
a DOM search is performed to locate matching elements. My question is very simple: how do I efficiently perform a series of actions (using the nice methods of jquery objects) on a DOM element I have located with jquery? Currently, I was doing (eg):
var previousHtml = $("#myDiv").html();
$("#myDiv").addClass("tangoClass");
$("#myDiv").html("bla bla bla");
//...
Basically, I was always referring to the element by writing $("#myDiv"). How can I repeatedly manipulate a DOM element (using jquery functions, rather than vanilla Javascript) in an efficient way? Does the following avoid the costly DOM searches?
var myDiv = $("#myDiv");
var previousHtml = myDiv.html();
myDiv.addClass("tangoClass");
myDiv.html("bla bla bla");
Or should I instead try chaining the jquery calls as much as possible, eg:
var previousHtml = $("#myDiv").addClass("tangoClass").html(); //saves me 1 $("#myDiv") call
$("#myDiv").html("bla bla bla");
Thank you for any insight. : )
lara
I also agree that chaining is the best method to use, but something else no one has address here is using .andSelf()(1) and .end()(2) while chaining.
The following adds the "border" class to both the div and the p contained within.
$("div").find("p").andSelf().addClass("border");
Using .end() "resets" the selector
$("div")
.find("p").addClass("myParagraph").end()
.find("span").addClass("mySpan");
Update: .andSelf() has been deprecated and essentially renamed to .addBack(), use it in the same manner.
Every time you use a jQuery function, it returns the full jQuery object from the initial query. This lets you chain actions together, so the actual query only happens the first time.
From your examples, it doesn't look like you ever use previousHtml, so you don't need to grab it at all. I think you can just do this:
$("#myDiv").html('bla bla bla').addClass('tangoClass');
It depends on which functions you are calling on that element, since not all functions will return the DOM element. However if all the functions you have to call will always return the DOM element, then it might certainly make your code more readable.
Yes I would recommend to use chaining, because the jQuery methods usually return the element you modified, so it doesn't need to be looked up in the DOM again. And I find it more readable, too (you know which operations belong to which element).
Just because no one mentioned it, using your first method will also work and save the DOM search.
However, chaining, as the others said, would be the more "proper" way of using the same element and applying different actions to it.
Good luck!
the two are the same.
var myDiv = $("#myDiv"); // $("#myDiv") runs document.getElementById,
// wraps the DOMElement, returns the wrapper.
myDiv.addClass("tangoClass"); // obviously reuses the object
myDiv.html("bla bla bla"); // ditto
chaining is exactly the same because jQuery methods return this, the object that they're attached to:
myDiv
.addClass("tangoClass")
.html("bla bla bla")
;
you can test this with (myDiv === myDiv.html("bla bla bla"))
to answer your question "which should I use": DRY (Don't Repeat Yourself) would suggest chaining. just don't forget readability (don't lump many method calls into a single line; my recipe for readability is above)

What jQuery annoyances should I be aware of as a Prototype user?

We're considering switching our site from Prototype to jQuery. Being all-too-familiar with Prototype, I'm well aware of the things about Prototype that I find limiting or annoying.
My question for jQuery users is: After working with jQuery for a while, what do you find frustrating? Are there things about jQuery that make you think about switching (back) to Prototype?
I think the only that gets me is that when I do a selection query for a single element I have to remember that it returns an array of elements even though I know there is only one. Normally, this doesn't make any difference unless you want to interact with the element directly instead of through jQuery methods.
Probably the only real issue I've ever ran into is $(this) scope problems. For example, if you're doing a nested for loop over elements and sub elements using the built in JQuery .each() function, what does $(this) refer to? In that case it refers to the inner-most scope, as it should be, but its not always expected.
The simple solution is to just cache $(this) to a variable before drilling further into a chain:
$("li").each(function() {
// cache this
var list_item = $(this);
// get all child a tags
list_item.find("a").each(function() {
// scope of this now relates to a tags
$(this).hide("slow");
});
});
My two pain points have been the bracket hell, can get very confusing
$('.myDiv').append($('<ul />').append($('<li />').text('content')));
My other common issue has to do with the use of JSON in jQuery, I always miss the last comma,
$('.myDiv').tabs({ option1:true, options2:false(, woops)});
Finally, I've been using jQuery for about 6 months now and I don't think I'll ever go back to prototypes. I absolutely love jQuery, and a lot of the tricks they use have helped me learn a lot. one cool trick that I like is using string literals for method calls, I never really did that too much with prototypes.
$('.myDiv')[(add ? 'add' : 'remove') + 'Class']('redText');
(The only thing I can think of is that this is the element instead of a jQuery object in $("...").each(function)-calls, as $(element) is more often used then just the element. And that extremly minor thing is just about it.
Example of the above (simplified and I know that there are other much better ways to do this, I just couldn't think of a better example now):
// Make all divs that has foo=bar pink.
$("div").each(function(){
if($(this).attr("foo") == "bar"){
$(this).css("background", "pink");
}
});
each is a function that takes a function as parameter, that function is called once for each matching element. In the function passed, this refers to the actual browser DOM-element, but I find that you often will want to use some jQuery function on each element, thus having to use $(this). If this had been set to what $(this) is, you'd get shorter code, and you could still access the DOM element object using this.get(0). Now I see the reason for things being as they are, namely that writing $(this) instead of this, is hardly that cumbersome, and in case you can do what you want to do with the DOM element the way it is is faster than the way it could have been, and the other way wouldn't be faster in the case you want $(this).)
I don't think there are any real gotchas, or even any lingering annoyances. The other answers here seem to confirm this - issues are caused simply by the slightly different API and different JavaScript coding style that jQuery encourages.
I started using Prototype a couple of years ago and found it a revelation. So powerful, so elegant. After a few months I tried out jQuery and discovered what power and elegance really are. I don't remember any annoyances. Now I am back working on a project using Prototype and it feels like a step back (to be fair, we're using Prototype 1.5.1).
If you reversed the question - "What Prototype annoyances should I be aware of as a jQuery user?" - you would get a lot more answers.
Nope. Nada. Nyet.
.each:
jQuery (you need Index, even if you're not using it):
$.each(collection, function(index, item) {
item.hide();
});
Prototype (you're usually using the item, so you can omit the index):
collection.each(function(item) {
item.hide();
});
This is really only an annoyance if you're doing a lot of DOM manipulation. PrototypeJs automatically adds its API to DOM Elements, so this works in prototypejs (jQuery of course doesn't do this):
var el = document.createElement("div");
el.addClassName("hello"); // addClassName is a prototypejs method implemented on the native HTMLElement
Even without running the native element through the $() function.
PS: Should note that this doesn't work in IE.

Categories

Resources