I have a long list of DOM elements that I'm grabbing attributes out of to save to an object.
It seems like an overuse of DOM manipulation to use the jQuery selector over and over.
var a = $('input[name=a]:checked').val(),
b = $('input[name=b]')is(':checked'),
c = $('input[name=c]').val();
I'm thinking there might be a way to do something like var $form = $('#form');
and then using $form.find('input[name=a]:checked')
or $form.children('input[name=b]')
or $form.filter('input[name=c]')
. But these examples are off. I believe that because I didn't select the elements themselves, that selecting their parent element will not prevent jQuery from having to repeatedly peruse the DOM. Is that true?
Another option may be to add another class to all of the elements specifically for this (:/), but for some reason that seems weird. It would give me an array, though, which I assume I could use to prevent repeated DOM traversing? Something like this:
var $formElementArray = $('.the_elements_you_wanted');
and then using filter?
var a = $formElementArray.filter('input[name=a]:checked').val(),
b = $formElementArray.filter('input[name=b]')is(':checked'),
c = $formElementArray.filter('input[name=c]').val();`
Is this the best way to do it? Is there a best practice for this kind of thing? It does seem a bit lame that I have to go add a class specifically to prevent too much DOM traversal since some of the elements I'm manipulating wouldn't have been grouped together otherwise, but if that's the case, c'est la vie.
As I suggested in my comments, you MUST test any performance questions like this if you really want to know the answer and you probably must test in several different browsers.
Here's a simple test case of five different scenarios: http://jsperf.com/scoped-selector-perf-test
Running these in Chrome v26, of the jQuery options (1-4), search for each item by a unique id is the fastest. 13x faster than the global search by name, 7x faster than filtering a common class, 4x faster than scoping to a form parent.
The plain javascript search by id is 17x faster than the fastest jQuery option and 223x faster than your original code. Similar results were seen in Firefox and IE10.
tag[name="xxx"]
is quite slowdocument.getElementById("a")
is significantly faster than $('#a')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With