Should hasClass precede removeClass - pure Javascript - javascript

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")

Related

Javascript setAttribute Vs jquery multiple attribute setter

I want to set so many attributes for multiple elements. Javascript always give better performance when comparing to jquery.
i want to know which one gives better performance when settling multiple attributes via jquery and javascript.
Jquery multiple attribute setter:
$(element).attr({'id': 'id1', 'index':1, 'value':10,'check':'checked'});
using javascript setAttribute :
element.setAttribute('id','id1');
element.setAttribute('index','1');
..................................
when am using javascript i need to write multiple lines. otherwise need to create custom function for this.
can anyone explain which one gives better performance ? and why ?
Thanks,
Siva
Here is a jsperf which tests setting of attributes. I'm not sure that it covers your situation but as the others said - pure javascript is a lot faster then using a library. (I'm not even sure that the jsperf is a valid one. I mean if it test what you need).
http://jsperf.com/aaa-setting-attribute
jQuery version is 66% slower then the pure javascript variant.
Computers cost much less than programmers.
Let's say:
Using pure js will make code run for 1ms, and programmer work 3 hours.
Using jQuery will make code run for 2ms and programmer work 1 minute
See profit?
You should probably be setting properties, not attributes, as they are more consistent across browsers and have a more consistent effect on DOM elements (sometimes setting an attribute affects the property, sometimes it doesn't). Setting the property nearly always has the desired affect (e.g. setting a checkbox to checked), setting the related attribute doesn't always.
You can also use a small function if you want to set multiple properties on an element:
function setProperties(element, props) {
for (var prop in props) {
if (props.hasOwnProperty(prop)) {
element[prop] = props[prop];
}
}
}
I can't see that it would be any slower than jQuery.
jQuery is a library, so I think it better than pure javascript. It help you to use javascript easier. I supposed that!
You can see the same question here
If you want to get all of attributes of element, you can see here also.

performance issue : storing a reference to DOM element vs using selectors

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.

Selectors: Id vs. context

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.

Which method should be used ideally - document.getElementById or document.forms[]?

I would like to know which of the following method is better?
document.getElementById or documennt.forms[]?
Which is the one that cshould be used regularly.
The focus is on performance.
Regards,
Naveen
I would use document.getElementById, you can be consistent for getting everything, not just forms by ID...this works for any and all elements, and it's the fastest way to select an object to boot.
I'm not sure about IE, but you can think of browsers as having a hashtable implementation mapping ID to element (since they have to be unique, or so says the spec, so the browser is free to assume that they are). This is what makes that selection so fast, and also what makes the action only work on the first element with an ID if you violated the spec and re-used it :)

How to check visibility of multiple div's in simpler way?

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();

Categories