Javascript setAttribute Vs jquery multiple attribute setter - javascript

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.

Related

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.

how to reference elements in CSS or JS files for fastest parsing?

I'm trying to improve a websites rendering speed.
Both CSS and JS files mostly reference elements like this:
Javascript:
$('.some_element').doSth()
CSS:
.some_element { /* do something */ }
Just curious - is this the optimal way of referencing elements in terms of javascript parsing and website rendering? Wouldn't it be better to do something like div.some_element?
Thanks for some infos!
If speed is a priority you might want to switch to vanilla javascript as much as you can. Native javascript is faster than jQuery.
If you want to keep your jQuery selector use parent context to make the search for the element more efficient. Example $('#parent').find(child)
You can find more tips on javascript an jquery optimization on the web:
http://engineeredweb.com/blog/10/12/3-tips-make-your-jquery-selectors-faster/
div.some_element will be different than .some_element, if you don't just have divs that use the some_element class.
Maybe compare render times using Chrome's built-in developer tools (or an alternative) to see if it helps you, but I doubt it'll be significant.
The fastest way to find a single element is usually with an id, not a class:
document.getElementById("whatever")
If you have to use jQuery (which is not as fast as plain javascript), then you would use:
$("#whatever")
If speed is really important, you can resolve the DOM element once when the page loads and just save the direct DOM reference so you don't have to find it when your code actually executes later.
As with all questions of performance, the only real way to answer a performance question is to benchmark a couple of implementation options and actually test which is faster.

Change all CSS property at run time

I have page which has several Button & images inside the <div>. I have such requirement :
On clicking over any image or button a div/page appears which contains all the css property and gives option to change the CSS property of concern element. eg. color, value, font size etc....
Is there any plugin available for that or do i need to create by own. I'd appreciate your suggestion
Thanks
you can refer these plugins and modify the source code according to requirement....
changecss
http://www.bramstein.com/projects/jsizes/
I doubt there will be such plugin which will know the ids/names of all your elements. The only way to have such plugin is if it searches by element type, but that will be really uncleaver, since it may list 100+ html elements, while you need to change only 5 (for example). It will be better and smarter to write it by yourself in my opinion.
jQuery makes such changes trivial, take a look at the .css() function. In order to get all elements you'll probably want to look at DOM traversal.
If you only need this for debugging purposes, you can use Chrom'e developper tools or Mozilla Firebug. They allow you to visualize and change CSS attributes on the fly.
If you need this for a shipping product, then good luck. It seems very hard, notably handling the CSS priority rules. Maybe you can get some reusable code from Firebug's code, which is mostly JS.
Use jquery for setting the desired css properties.
Use selector and google for setting css properties using Jquery.

When to use Vanilla JavaScript vs. jQuery?

I have noticed while monitoring/attempting to answer common jQuery questions, that there are certain practices using javascript, instead of jQuery, that actually enable you to write less and do ... well the same amount. And may also yield performance benefits.
A specific example
$(this) vs this
Inside a click event referencing the clicked objects id
jQuery
$(this).attr("id");
Javascript
this.id;
Are there any other common practices like this? Where certain Javascript operations could be accomplished easier, without bringing jQuery into the mix. Or is this a rare case? (of a jQuery "shortcut" actually requiring more code)
EDIT : While I appreciate the answers regarding jQuery vs. plain javascript performance, I am actually looking for much more quantitative answers. While using jQuery, instances where one would actually be better off (readability/compactness) to use plain javascript instead of using $(). In addition to the example I gave in my original question.
this.id (as you know)
this.value (on most input types. only issues I know are IE when a <select> doesn't have value properties set on its <option> elements, or radio inputs in Safari.)
this.className to get or set an entire "class" property
this.selectedIndex against a <select> to get the selected index
this.options against a <select> to get a list of <option> elements
this.text against an <option> to get its text content
this.rows against a <table> to get a collection of <tr> elements
this.cells against a <tr> to get its cells (td & th)
this.parentNode to get a direct parent
this.checked to get the checked state of a checkbox Thanks #Tim Down
this.selected to get the selected state of an option Thanks #Tim Down
this.disabled to get the disabled state of an input Thanks #Tim Down
this.readOnly to get the readOnly state of an input Thanks #Tim Down
this.href against an <a> element to get its href
this.hostname against an <a> element to get the domain of its href
this.pathname against an <a> element to get the path of its href
this.search against an <a> element to get the querystring of its href
this.src against an element where it is valid to have a src
...I think you get the idea.
There will be times when performance is crucial. Like if you're performing something in a loop many times over, you may want to ditch jQuery.
In general you can replace:
$(el).attr('someName');
with:
Above was poorly worded. getAttribute is not a replacement, but it does retrieve the value of an attribute sent from the server, and its corresponding setAttribute will set it. Necessary in some cases.
The sentences below sort of covered it. See this answer for a better treatment.
el.getAttribute('someName');
...in order to access an attribute directly. Note that attributes are not the same as properties (though they mirror each other sometimes). Of course there's setAttribute too.
Say you had a situation where received a page where you need to unwrap all tags of a certain type. It is short and easy with jQuery:
$('span').unwrap(); // unwrap all span elements
But if there are many, you may want to do a little native DOM API:
var spans = document.getElementsByTagName('span');
while( spans[0] ) {
var parent = spans[0].parentNode;
while( spans[0].firstChild ) {
parent.insertBefore( spans[0].firstChild, spans[0]);
}
parent.removeChild( spans[0] );
}
This code is pretty short, it performs better than the jQuery version, and can easily be made into a reusable function in your personal library.
It may seem like I have an infinite loop with the outer while because of while(spans[0]), but because we're dealing with a "live list" it gets updated when we do the parent.removeChild(span[0]);. This is a pretty nifty feature that we miss out on when working with an Array (or Array-like object) instead.
The correct answer is that you'll always take a performance penalty when using jQuery instead of 'plain old' native JavaScript. That's because jQuery is a JavaScript Library. It is not some fancy new version of JavaScript.
The reason that jQuery is powerful is that it makes some things which are overly tedious in a cross-browser situation (AJAX is one of the best examples) and smooths over the inconsistencies between the myriad of available browsers and provides a consistent API. It also easily facilitates concepts like chaining, implied iteration, etc, to simplify working on groups of elements together.
Learning jQuery is no substitute for learning JavaScript. You should have a firm basis in the latter so that you fully appreciate what knowing the former is making easier for you.
-- Edited to encompass comments --
As the comments are quick to point out (and I agree with 100%) the statements above refer to benchmarking code. A 'native' JavaScript solution (assuming it is well written) will outperform a jQuery solution that accomplishes the same thing in nearly every case (I'd love to see an example otherwise). jQuery does speed up development time, which is a significant benefit which I do not mean to downplay. It facilitates easy to read, easy to follow code, which is more than some developers are capable of creating on their own.
In my opinion then, the answer depends on what you're attempting to achieve. If, as I presumed based on your reference to performance benefits, you're after the best possible speed out of your application, then using jQuery introduces overhead every time you call $(). If you're going for readability, consistency, cross browser compatibility, etc, then there are certainly reasons to favor jQuery over 'native' JavaScript.
There's a framework called... oh guess what? Vanilla JS. Hope you get the joke... :D It sacrifices code legibility for performance... Comparing it to jQuery bellow you can see that retrieving a DOM element by ID is almost 35X faster. :)
So if you want performance you'd better try Vanilla JS and draw your own conclusions. Maybe you won't experience JavaScript hanging the browser's GUI/locking up the UI thread during intensive code like inside a for loop.
Vanilla JS is a fast, lightweight, cross-platform framework for
building incredible, powerful JavaScript applications.
On their homepage there's some perf comparisons:
There's already an accepted answer but I believe no answer typed directly here can be comprehensive in its list of native javascript methods/attributes that has practically guaranteed cross-browser support. For that may I redirect you to quirksmode:
http://www.quirksmode.org/compatibility.html
It is perhaps the most comprehensive list of what works and what doesn't work on what browser anywhere. Pay particular attention to the DOM section. It is a lot to read but the point is not to read it all but to use it as a reference.
When I started seriously writing web apps I printed out all the DOM tables and hung them on the wall so that I know at a glance what is safe to use and what requires hacks. These days I just google something like quirksmode parentNode compatibility when I have doubts.
Like anything else, judgement is mostly a matter of experience. I wouldn't really recommend you to read the entire site and memorize all the issues to figure out when to use jQuery and when to use plain JS. Just be aware of the list. It's easy enough to search. With time you will develop an instinct of when plain JS is preferable.
PS: PPK (the author of the site) also has a very nice book that I do recommend reading
When:
you know that there is unflinching cross-browser support for what you are doing, and
it is not significantly more code to type, and
it is not significantly less readable, and
you are reasonably confident that jQuery will not choose different implementations based on the browser to achieve better performance, then:
use JavaScript. Otherwise use jQuery (if you can).
Edit: This answer applies both when choosing to use jQuery overall versus leaving it out, as well as choosing whether to to use vanilla JS inside jQuery. Choosing between attr('id') and .id leans in favor of JS, while choosing between removeClass('foo') versus .className = .className.replace( new Regexp("(?:^|\\s+)"+foo+"(?:\\s+|$)",'g'), '' ) leans in favor of jQuery.
Others' answers have focused on the broad question of "jQuery vs. plain JS." Judging from your OP, I think you were simply wondering when it's better to use vanilla JS if you've already chosen to use jQuery. Your example is a perfect example of when you should use vanilla JS:
$(this).attr('id');
Is both slower and (in my opinion) less readable than:
this.id.
It's slower because you have to spin up a new JS object just to retrieve the attribute the jQuery way. Now, if you're going to be using $(this) to perform other operations, then by all means, store that jQuery object in a variable and operate with that. However, I've run into many situations where I just need an attribute from the element (like id or src).
Are there any other common practices
like this? Where certain Javascript
operations could be accomplished
easier, without bringing jQuery into
the mix. Or is this a rare case? (of a
jQuery "shortcut" actually requiring
more code)
I think the most common case is the one you describe in your post; people wrapping $(this) in a jQuery object unnecessarily. I see this most often with id and value (instead using $(this).val()).
Edit: Here's an article that explains why using jQuery in the attr() case is slower. Confession: stole it from the tag wiki, but I think it's worth mentioning for the question.
Edit again: Given the readability/performance implications of just accessing attributes directly, I'd say a good rule of thumb is probably to try to to use this.<attributename> when possible. There are probably some instances where this won't work because of browser inconsistencies, but it's probably better to try this first and fall back on jQuery if it doesn't work.
If you are mostly concerned about performance, your main example hits the nail on the head. Invoking jQuery unnecessarily or redundantly is, IMHO, the second main cause of slow performance (the first being poor DOM traversal).
It's not really an example of what you're looking for, but I see this so often that it bears mentioning: One of the best ways to speed up performance of your jQuery scripts is to cache jQuery objects, and/or use chaining:
// poor
$(this).animate({'opacity':'0'}, function() { $(this).remove(); });
// excellent
var element = $(this);
element.animate({'opacity':'0'}, function() { element.remove(); });
// poor
$('.something').load('url');
$('.something').show();
// excellent
var something = $('#container').children('p.something');
something.load('url').show();
I've found there is certainly overlap between JS and JQ. The code you've shown is a good example of that. Frankly, the best reason to use JQ over JS is simply browser compatibility. I always lean toward JQ, even if I can accomplish something in JS.
This is my personal view, but as jQuery is JavaScript anyway, I think theoretically it cannot perform better than vanilla JS ever.
But practically it may perform better than hand-written JS, as one's hand-written code may be not as efficient as jQuery.
Bottom-line - for smaller stuff I tend to use vanilla JS, for JS intensive projects I like to use jQuery and not reinvent the wheel - it's also more productive.
The first answer's live properties list of this as a DOM element is quite complete.
You may find also interesting to know some others.
When this is the document :
this.forms to get an HTMLCollection of the current document forms,
this.anchors to get an HTMLCollection of all the HTMLAnchorElements with name being set,
this.links to get an HTMLCollection of all the HTMLAnchorElements with href being set,
this.images to get an HTMLCollection of all the HTMLImageElements
and the same with the deprecated applets as this.applets
When you work with document.forms, document.forms[formNameOrId] gets the so named or identified form.
When this is a form :
this[inputNameOrId] to get the so named or identified field
When this is form field:
this.type to get the field type
When learning jQuery selectors, we often skip learning already existing HTML elements properties, which are so fast to access.
As usual I'm coming late to this party.
It wasn't the extra functionality that made me decide to use jQuery, as attractive as that was. After all nothing stops you from writing your own functions.
It was the fact that there were so many tricks to learn when modifying the DOM to avoid memory leaks (I'm talking about you IE). To have one central resource that managed all those sort of issues for me, written by people who were a whole lot better JS coders than I ever will be, that was being continually reviewed, revised and tested was god send.
I guess this sort of falls under the cross browser support/abstraction argument.
And of course jQuery does not preclude the use of straight JS when you needed it. I always felt the two seemed to work seamlessly together.
Of course if your browser is not supported by jQuery or you are supporting a low end environment (older phone?) then a large .js file might be a problem. Remember when jQuery used to be tiny?
But normally the performance difference is not an issue of concern. It only has to be fast enough. With Gigahertz of CPU cycles going to waste every second, I'm more concerned with the performance of my coders, the only development resources that doesn't double in power every 18 months.
That said I'm currently looking into accessibility issues and apparently .innerHTML is a bit of a no no with that. jQuery of course depends on .innerHTML, so now I'm looking for a framework that will depend on the somewhat tedious methods that are allowed. And I can imagine such a framework will run slower than jQuery, but as long as it performs well enough, I'll be happy.
Here's a non-technical answer - many jobs may not allow certain libraries, such as jQuery.
In fact, In fact, Google doesn't allow jQuery in any of their code (nor React, because it's owned by Facebook), which you might not have known until the interviewer says "Sorry, but you cant use jQuery, it's not on the approved list at XYZ Corporation". Vanilla JavaScript works absolutely everywhere, every time, and will never give you this problem. If you rely on a library yes you get speed and ease, but you lose universality.
Also, speaking of interviewing, the other downside is that if you say you need to use a library to solve a JavaScript problem during a code quiz, it comes across like you don't actually understand the problem, which looks kinda bad. Whereas if you solve it in raw vanilla JavaScript it demonstrates that you actually understand and can solve every part of whatever problem they throw in front of you.
$(this) is different to this :
By using $(this) you are ensuring the jQuery prototype is being passed onto the object.

Javascript: Performance of .className Changes vs. .style Changes

Back in 2005, Quirksmode.com released this article:
http://www.quirksmode.org/dom/classchange.html
that showed "proof" that changing the style of an element by changing its class (ie. "elem.className = x") was almost twice as fast as changing its style via its style property (ie. "elem.style.someStyle = x"), except in Opera. As a result of that article, we started using a className-based solution to do things like showing/hiding elements on our site.
The problem is, one of our developers would much rather use jQuery's equivalent methods for this kind of thing (ie. "$(something).hide()"), and I'm having a hard time convincing him that our className-based function is worth using, as I can only find a single article written four years ago.
Does anyone know of any more recent or more comprehensive investigations in to this issue?
Micro-optimization is evil. I think unless you are hiding a seriously large amount of elements at once or something, the difference in milliseconds is unimportant if by some chance that article is still relevant nowadays.
With that in mind, I would go with jQuery's methods as they are battle tested and more concise.
There is a flaw in the benchmark that article uses.
In my personal experience I've never seen a case where updating a className outperforms inline style setting. I have no concrete proof of this (I do vaguely remember an article I'm going to try to dig up), but I have noticed that large clientside apps (for example gmail, or google maps) prefer setting inline styles to classNames, and it was in the context of analysis of these apps that I first heard of the speed increase in doing so.
Note that I am not promoting one over the other: setting the className dynamically goes a long way in terms of maintainability/readability and separating concerns.
While I generally agree with the practice of using classes over style attributes for many reasons. Performance is one but consistency is another. I've often seen people do things like:
function toggle(element) {
element.style.display = element.style.display == 'none' ? 'block' : 'none';
}
(or the jQuery equivalent)
Seems reasonable right? It is until you apply it to table elements that have default display values of, for example, table-cell (not block). The class method:
.hidden { display: none; }
...
function toggle(element) {
$(element).toggleClass("hidden");
}
is much, much better for this and other reasons.
But the jQuery methods like hide() are an exception to this. They handle display setting correctly and give you the animations.
Test it yourself. There's a tester on the page you linked. Test performance on your target browsers to determine the best method to use, performance-wise.
Personally, I would choose readability over performance. Besides, the tides may turn later (if they haven't already**). If it makes sense to use a class (i.e. you use the style for many elements), you might as well use a class. If the CSS is for an animation on an element, use style. For either, prefer jQuery's functions as they are (1) more consistent and (2) more robust and tested.
**For Opera 10, at least, the speed has definitely improved. The tests are 5/12ms locally for Opera 10, 57/88ms for Firefox 3, 14/36ms for Google Chrome, and 125/118ms (!) for IE7. IE7 (perhaps your target browser) has about the same speed for either, with style changing slightly in the lead!
Premature optimization is the root of all evil.
Are you hiding hundreds of elements per second? If not, I'd say there are bigger fish to fry. Worse, a study done in 2005 says nothing about the performance of modern browsers. No IE7 or 8, No Firefox 3 (was 2 even out?), no Chrome.
But if you insist and want your fellow colleagues to follow suit, you should write a jQuery plugin that "hide()"'s using a class instead of a style.
No, but I can tell you that jQuery.hide() can hide an element with a smooth effect. This cannot be done by changing the className.
You are talking about client code, it runs in the user browser so it does not load your server. I ignore the javascript in your client side but I guess is not crunching much CPU.
Your coleague use of jQuery is probably not having a great impact while it results in a more readable code. Therefore I think he does not need to be convinced at all.

Categories