When I want to run a jQuery function on a single element that has the class .pizza, I do this:
$('.pizza').hide();
What is the difference between that and using first() or eq(0)?
$('.pizza').eq(0).hide();
My question comes because I want to cache the element into a variable to use it many times, and I don't know if it is a better practice to do:
var element_pizza=$('.pizza').eq(0);
Or just simply:
var element_pizza=$('.pizza');
Note: When I mean on a single element, I mean that there is only one element with the class pizza in the DOM.
Thanks for your time.
There is no difference when the set contains only one match.
Using .eq() would only be to select one specific match from a set. If the set has one element, then they will be equivalent.
In fact, it is a waste to use .eq(0) if the set contains one element because that will cause a new jQuery object to be created.
Related
I prefer to bind all my DOM elements at the top of my code so that the ID or class reference is only hard coded once, even though the element is used multiple times within the code. Something like this:
var startButton = "#startButton";
var closeButtons = ".button.close";
That works well with selectors, such as document.querySelector. The challenge occurs when I'm about to compare an element ID to one of the static variables above, like for instance during a click event:
e.target.id == startButton
Since the variable startButton contains a sharp, I would have to do something like this:
e.target.id == startButton.replace('#', '')
This is obviously not the ideal way of handling things, so I'm wondering if there's a better way to bind DOM elements for later use?
Please note that I did consider retrieving the elements using a selector right away, like document.querySelector, but that prevents me from manipulating the elements later on.
EDIT: My note above turns out to be wrong. It's totally possible to manipulate the elements later on. So the question is whether it's better to store selectors in variables, or to store nodes in variables. As pointed out below, the DOM element might not exist while it's being declared, so it might be better to store the selector in a variable, like I'm doing above.
For the specific example in your question, you can use .matches():
if (e.target.matches(startButton))
The .matches() DOM API takes a selector as its argument.
I recently came across this question: How do I check if an element is hidden in jQuery?
The currently accepted answer seems to indicate that $('element').is(':hidden') is preferable to $('element:hidden') because the :hidden filter is only being applied to a single element.
But... Calling .is() also adds extra overhead as you are calling an another function.
This got me thinking, does the above reasoning for using .is() hold true if the selector is a set of elements?
And what about more extreme cases? Take the following test case:
$('element.class1:not(.class2):visible[rel="foo"]')
Is it best to leave those in the selector? Or move them all into a single filter call:
$('element').filter('.class1:not(.class2):visible[rel="foo"]')
Or is it better to chain them?
$('element').is('.class1').not('.class2').is(':visible').filter('[rel="foo"]')
The currently accepted answer seems to indicate that $('element').is(':hidden') is preferable to $('element:hidden') because the :hidden filter is only being applied to a single element.
I don't read it that way at all, and assuming you're dealing with a string, then $("some-selector:hidden") isn't applied only to a single element; it's applied to all elements matching some-selector.
Or is it better to chain them?
$('element').is('.class1').not('.class2').is(':visible').filter('[rel="foo"]')
That will fail, since is returns a boolean:
.is(selector)
Description: Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.
If you want to select elements matching multiple criteria, it's fine to put those criteria in the selector string. The only real question you should ask yourself is whether to use :hidden and other jQuery-isms in the string, since it means that jQuery can't pass the selection off to the browser's built-in (read: fast) selector engine, and has to do the work itself.
For that reason, with that example, you might prefer to move the jQuery-isms out of it:
$('element.class1:not(.class2)[rel="foo"]').filter(":visible")
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.
I know in jQuery if we use ID to select elements,it's so efficient.I have a question about this selectors:
please consider this 3 selectors:
$('#MyElement')
$('#Mytbl #MyElement')
$('#Mytbl .MyClass')
which one is faster and why?How I can check the time elapsed to select my element in jQuery?
A direct ID selector will always be the fastest.
I've created a simple test case based on your question...
http://jsperf.com/selector-test-id-id-id-id-class
Selecting nested ID's is just wrong, because if an ID is unique (which it should be), then it doesn't matter if it's nested or not.
this is the way to stop times between some javascript calls
selectorTimes = [];
var start = new Date().getTime();
$('#MyElement')
selectorTimes.push(new Date().getTime()-start);
start = new Date().getTime()
$('#Mytbl #MyElement')
selectorTimes.push(new Date().getTime()-start);
start = new Date().getTime()
$('#Mytbl .MyClass')
selectorTimes.push(new Date().getTime()-start);
console.log(selectorTimes);
i think the second selector is not efficient, if you have a domid select this directly:
$('#MyElement')
The first one is the fastest, simply because it only has 1 property to look for. However,
document.getElementById("MyElement")
is even faster, though. It's native javascript, and unlike jQuery, the browser immediately knows what you want to do, instead of having to run through a load of jQuery code to figure out what it is you're looking for, in the first place.
You can use jsPerf to run a speed test, to compare the functions: Test Case. Results:
$('#MyElement')
Ops/sec: 967,509
92% slower
$('#Mytbl #MyElement')
Ops/sec: 83,837
99% slower
$('#Mytbl .MyClass')
Ops/sec: 49,413
100% slower
document.getElementById("MyElement")
Ops/sec: 10,857,632
fastest
Like expected, the native getter is the fastest, followed by the jQuery getter with only 1 selector at less than 10% of the native speed. The jQuery getters with 2 parameters don't even get close to the operations per second of native code, especially the class selector, since classes are usually applied to multiple elements, compared to ID's. (Native ID selectors stop searching after they've found one element, I'm not sure if jQuery does, too.)
A couple things:
More selectors = slower search. If you can get your desired result with fewer predicates, do so.
Getting an element by ID is quicker than getting by a class. getElementById is a core function of JavaScript that is heavily optimised because it is used so frequently. Leverage this when possible.
The space selector (' ') is much more costly than the child selector ('>'). If you can use the child selector, do so.
These rules apply to CSS as they do JavaScript and jQuery.
Here you are. See the comments on top of each example:
//fastest because it is just one id lookup: document.getElementById("MyElement") with no further processing.
$('#MyElement')
//a little slower. JQuery interprets selectors from right to left so it first looks up for #MyElement and then checks if it is hosted in #Mytbl
$('#Mytbl #MyElement')
//the slowest of all. JQuery interprets selectors from right to left so it first finds all elements with .MyClass as their class and then searches for those hosted in #Mytbl.
$('#Mytbl .MyClass')
If you can, always use just the id (like the first example) but if you have to have multiple selectors and classes chained together, try to put the most strict one at the right. For example an id. Because JQuery interprets selectors from right to left.
Also, if you need nested selectors, it's faster to use $().find().find()
http://jsperf.com/selector-test-id-id-id-id-class/2
$('#Mytbl .MyClass')
$('#Mytbl').find('.MyClass')
The latter is about 65% faster.
Obviously the first one, $("#MyElement") is faster than other 2.
Accessing an element with its id always faster but sometimes we had to find some element in some container. In that case we prefer .find() or .filter() (depending upon situation).
The difference between selectors depends on browser to browser. e.g. if you access through class on IE it would be slower than FF. FF is faster when accessing an element with class rather than ID.
In your second example, i.e. $("#mytbl #MyElement"), here you are finding #MyElement under #mytbl which is legal but not appropriate way. Since you already know the ID of the element (assuming you have only one element with this id on your page) so its better to use $("#MyElement"). $("#mytbl #MyElement") will read #mytbl first and traverse to find #MyElement under it hence time consuming and slow.
To test different cases you can write small snippet to read/access atleast 10000 elements in a loop otherwise it would be hard to determine which way is faster.
The fastest will be:
$('#Mytbl', '#MytblContainer' );
because in this case, jquery don't have to search the whole dom tree to find '#Mytbl'. It will search in the scope given only. IE it will serach in '#MytblContainer' only .
I would say that the first one is the fastest because you're simply searching for one id.
And
$('#Mytbl .MyClass')
is the slowest because you're not specifying the type of element that has the class "MyClass"
I know jQuery doesn’t cache collections of element, f.ex calling:
$('.myclass').html('hello');
$('.myclass').html('bye');
Will make jQuery climb the DOM twice.
But how about cached DOM nodes?
var elems = document.querySelectorAll('.myclass');
$(elems).html('hello');
$(elems).html('bye');
Will jQuery cache those internally, or will they be equally slow as the first example?
To clarify: will jQuery keep a reference to elems and cache $(elems) internally so it won’t have to apply the same $() wrapper every time?
Something like:
cache = {}
constructor = function(collection)
if collection in cache
return cache[collection]
else construct(collection)
Assuming I've understood your question correctly, then no, jQuery won't keep a reference to the selected nodes beyond the statement that uses them:
$('.myclass').html('hello'); //Select all .myclass elements, then change their HTML
$('.myclass').html('bye'); //Select all .myclass elements, then change their HTML again
If you maintain a reference to those selected nodes separately, it will be faster:
var elems = document.querySelectorAll('.myclass'); //Select all .myclass elements
$(elems).html('hello'); //Change their HTML (no need to select them)
$(elems).html('bye'); //Change their HTML (no need to select them)
The difference won't be massive (unless your DOM is very complicated) but there will be a difference:
Update
will jQuery keep a reference to elems and cache $(elems) internally so
it won’t have to apply the same $() wrapper every time?
No, it won't. As stated above, the reference to the matched set of elements will not be maintained beyond the statement to which it applies. You can improve the performance of your code by keeping a reference to jQuery objects that are used throughout, rather than selecting them again each time, or even wrapping a stored set of native DOM nodes in a jQuery object each time.
If "cache" means "keep the DOM elements in the internal collection for that jQuery object" .. then yes.
Imagine
jq = $(elementListOrSelector)
where jq[0..jq.length-1] evaluate to the respectively DOM element. For instance, jq[0] evaluates to the first DOM element represented by the jQuery object, if any. Note that this collection is not magically changed once it has been built (and the way in which it was built does not matter).
However there is no "cache" outside of simply keeping the immediate results for that particular jQuery object.