Currently i'm using below code which works well.
$("#topperAtBaseLevel:visible, #lowerAtBaseLevel:visible, #midAtBaseLevel").hide();
any optimised code? (i cant use same class)
i mean how to use :visible rightly?
That is the way to achieve what you're going for. You are using the selectors correctly and efficiently.
You could make it a little faster if you maintained an array of the ID's of the tags that need to be hidden, and then construct your selector dynamically to find by ID. (This would be faster even though the selector might be longer. Selecting by ID is very fast.)
But, the optimization is not needed, is it? We're talking about going from lightening fast to double lightening fast. A super-duper jQuery pro would just do what you've done.
That code seems perfect; you are using :visible correctly.
You can take a look at the jQuery :visible selector help page if you want to know exactly how it works, but in a few words it selects visible elements =)
Well, all I can think of, is:
$('[id$="AtBaseLevel"]:visible').hide();
That would match any element whose ID ends in AtBaseLevel. Mind you, shorter does not mean faster, since ID lookups are about as fast as it gets. Attribute-based selectors are not that optimised.
You can do it like this:
$("#topperAtBaseLevel, #lowerAtBaseLevel, #midAtBaseLevel").filter(":visible").hide();
However, this results in everything being hidden, calling .hide() on a hidden element is fine, nothing wrong there, so it could just be this:
$("#topperAtBaseLevel, #lowerAtBaseLevel, #midAtBaseLevel").hide();
Related
I saw this pattern being used in some code...
currency = $(document.getElementById('currency'));
Which is expect is functionally equivalent to...
currency = $('#currency');
I am guessing the idea is to make the selector faster, as it does not need to parse the selection string... but does it really make a discernible difference? Is there something else at play I have not considered?
Why would someone use this kind of pattern?
Internally, when parsing the selector string passed, jQuery automatically detects that you passed an id selector and calls document.getElementById for you.
So, when you're fetching the element yourself prior the call to jQuery, you're only saving the selector parsing portion, but that's negligible for most use cases.
See source
No sense to use first sintax -- both do the same ( at second part you skip parsing for jq-query ) -- also jq can cache requests -- so just right $('#..') and keep your code clean
http://jsperf.com/document-getelementbyid-as-jquery-selector
I saw this pattern being used in some code...
currency = $(document.getElementById('currency'));
Which is expect is functionally equivalent to...
currency = $('#currency');
Now, yes. It didn't used to be, back when IE6 and IE7 were still on the scene. The getElementById in IE7 and earlier was broken and would return elements with a matching name as well as a matching id. jQuery (1.x) has intelligence built into it to deal with broken old browsers. Thankfully, Microsoft fixed this in IE8.
I am guessing the idea is to make the selector faster, as it does not need to parse the selection string... but does it really make a discernible difference?
It probably makes an actual difference, but not in a way that translates to anything perceptible in the real world. The only way to know for sure is to test it on a DOM that's representative of the ones you want to know the answer for, and on the browsers that you want to know the answer for. (JSPerf seems to be having issues at the moment, though.)
Here's a test that doesn't use a representative DOM suggesting a significant percentage difference:
...but again, in real world terms unless you're doing this millions of times in a loop, it's not going to matter. Also note that what's being tested is so fast that error margins are likely to be large.
$(document.getElementById('currency')); is less readable and in the end there will be getElementById called anyway. You will not see it's effect in most cases (element is cached and will be called only once).
It uses document.querySelector() if is supported, and if not uses document.getElementById()
In my opinion, for non-jquery purpopses, document.querySelector() is better (for me)
document.querySelector("#id .class > tag.nested");
To remove the class, I use
getElementsByClassName("myclass1")[i].classList.remove("myclass2")
based on HTML5 Techniques. (I know that's not for IE9-, that's for browsers only).
As far as I know it is absolutely fine do not check if class exists. Right?
However, in my case there are many items with myclass1 on the page where I want to remove myclass2, but most of them (let's say 90%) do not have myclass2.
Will checking if the class myclass2 exists will help to increase the performance as checking if exists could be much faster than delete? (still not sure about my last statement)
What would you do in my case?
Thank you.
As far as I know it is absolutely fine do not check if class exists. Right?
Yes. remove does only remove the tokens it finds.
Will checking if the class myclass2 exists will help to increase the performance as checking if exists could be much faster than delete?
Hardly, because it would be searched twice in the list.
getElementsByClassName supports multiple classes, so if you want to streamline it, you can include both "myclass1" and "myclass2" in as parameters and it will return only those elements that have both (see here for more info: https://developer.mozilla.org/en-US/docs/Web/API/document.getElementsByClassName).
So, in your case, I would recommend using this:
getElementsByClassName("myclass1 myclass2")[i].classList.remove("myclass2")
I am new to javascript and jQuery.
i just want to know that is there any way create something different ,say structured dom language ?
in jQuery to select all div
var divs = $("div");
i want to know the possibility of something like this
var SDL = new SDL();
var div = SDL.query("select div from document"); //or something like that ..
or to select a div with ID
var div = SDL.query("select div from document where id='divID'");
looking mad right ?
i am sure i will not care about the downvotes for the question , but i need to know why this is not good ? or why its is not posible ?
Please say something on this ...
Thank you.
It's not good because it's pointless to implement or use. It would make the jQuery library much larger than it needs to be, and CSS selectors are clear enough anyway, as well as being far more concise.
It is possible, but what you're describing is actually pretty close to CSS selectors, but with a couple of extraneous words thrown in with some formatting changes.
In your "SDL" selector, it would simply be replaced by:
div#id
Why go through the trouble of writing a whole sentence to do the same thing? There may be a third party SQL-like selector library, in the same way Sizzle is a CSS selector library, however I've never heard or seen of one personally.
An SDL would also be much slower than using CSS-based selectors, as the string is more complex and has more garbage in it than a CSS selector string. More importantly, however, you wouldn't get the native speedups that querySelectorAll() et al give when used natively.
So in my app, the user can create some content inside certain div tags, and each content, or as I call them "elements" has its own object. Currently I use a function to calculate the original div tag that the element has been placed inside using jquery selectors, but I was wondering in terms of performance, wouldn't it be better to just store a reference to the div tag once the element has been created, instead of calculating it later ?
so right now I use something like this :
$('.div[value='+divID+']')
but instead I can just store the reference inside the element, when im creating the element. Would that be better for performance ?
If you have lots of these bindings it would be a good idea to store references to them. As mentioned in the comments, variable lookups are much much faster than looking things up in the DOM - especially with your current approach. jQuery selectors are slower than the pure DOM alternatives, and that particular selector will be very slow.
Here is a test based on the one by epascarello showing the difference between jQuery, DOM2 methods, and references: http://jsperf.com/test-reference-vs-lookup/2. The variable assignment is super fast as expected. Also, the DOM methods beat jQuery by an equally large margin. Note, that this is with Yahoo's home page as an example.
Another consideration is the size and complexity of the DOM. As this increases, the reference caching method becomes more favourable still.
A local variable will be super fast compared to looking it up each time. Test to prove it.
jQuery is a function that builds and returns an object. That part isn't super expensive but actual DOM lookups do involve a fair bit of work. Overhead isn't that high for a simple query that matches an existing DOM method like getElementById or getElementsByClassName (doesn't in exist in IE8 so it's really slow there) but yes the difference is between work (building an object that wraps a DOM access method) and almost no work (referencing an existing object). Always cache your selector results if you plan on reusing them.
Also, the xpath stuff that you're using can be really expensive in some browsers so yes, I would definitely cache that.
Stuff to watch out for:
Long series of JQ params without IDs
Selector with only a class in IE8 or less (add the tag name e.g. 'div.someClass') for a drastic improvement - IE8 and below has to hit every piece of HTML at the interpreter level rather than using a speedy native method when you only use the class
xpath-style queries (a lot of newer browsers probably handle these okay)
When writing selectors consider how much markup has to be looked at to get to it. If you know you only want divs of a certain class inside a certain ID, do one of these $('#theID div.someClass') rather than just $('div.someClass');
But regardless, just on the principle of work avoidance, cache the value if you're going to use it twice or more. And avoid haranguing the DOM with repeated requests as much as you can.
looking up an element by ID is super fast. i am not 100% sure i understand your other approach, but i doubt it would be any better than a simple lookup of an element by its id, browsers know how to this task best. from what you've explained I can't see how your approach would be any faster.
I use jQuery.
I have been reading a lot about selector performance and optimizing our AJAX app. I am looking to improve my selector performance. I know all the jquery performance tips. I haven't found an exact answer to a question I have. I am using almost every current jquery performance tip and yet my app still seems to lag quite a bit.
So, to optimize I am starting with selectors.
My question is: Is descending from a context to target an id faster than just targeting the id? I can't tell much of a difference.
Example:
Is
$('#childId', $higherElm);
faster than just
$('#childId');
????
Thanks in advance.
As seen in the jQuery source, $('#id') does simply document.getElementById, while $('#id', context) does $(context).find('#id'). So the first is faster.
According to this article, it's faster to have fewer, more direct selectors. #id is better than #id #child, at least in css...
Selecting an ID is the absolute fastest selection you can do.
Adding anything else will just slow it down.
When you're selecting by "id", context doesn't matter much because the engine's going to call getElementById() anyway. Context semantically matters of course, but that check should be pretty fast. (I suppose that in that light, having the context should be slightly slower, but you can't stop doing that if it's got actual meaning for your pages.)
Not sure if the syntax you describe above would be beneficial, but on http://www.artzstudio.com/2009/04/jquery-performance-rules/ it does state in rule #5 that using sub-queries is faster (which makes sense)... they demonstrate it using the $higherElm.find() syntax, though.
In your example - since it maps directly to getElementById which is a native function call - I don't think you'll see much of an improvement. However, selectors that target sets of elements (hence looping), would probably see some, or major, benefit.