tags:

views:

87

answers:

5

Hi,

Do you think jquery could help me get the following script work faster? Thanks!

window.onload=function colorizeCheckedRadios(){                     
    var inputs = document.getElementsByTagName("input");
    if (inputs) {
        for (var i = 0; i < inputs.length; ++i) {
            if(inputs[i].checked&&inputs[i].type=="radio"){
                inputs[i].parentNode.parentNode.style.backgroundColor='#FCE6F4';
            }
        }       
    }
}
+8  A: 

Faster, I don't know. Cleaner and cross browser: yes

$(function() {
    $('input:radio:checked').parent().parent().css('background-color', '#FCE6F4');
});
Darin Dimitrov
+1 for cleanness and compatibility. Faster, most likely not -- definitely not in browsers where `querySelectorAll()` is unavailable.
Andy E
Thanks for all the quick answers! I implemented the code and to me it seems a bit faster. I'm on Firefox 3.6. Thanks a lot! It is awesome clean code.
Haluk
It might actually be a bit faster on browsers that implement `querySelectorAll`, although the speed difference should be negligible anyway.
musicfreak
each .parent() call is causing a whole new loop through all the inputs found. In case you have alot, then you'd want to write this so you only loop once.
seanmonstar
+2  A: 

You can do this version with jQuery:

$(function() {
  $(":radio:checked").parent().parent().css('background-color', '#FCE6F4');
});

So, yes, you can slim it down a bit :)

If you knew what the parent you wanted was, say a <span>, you can do this:

$(function() {
  $(":radio:checked").closest('span').css('background-color', '#FCE6F4');
});
Nick Craver
A: 

Yes, probably. jQuery has the jQuery.ready() method which executes the function when the DOM is complete, and not when all the images are loaded. See: http://15daysofjquery.com/quicker/4/

Dor
Why the downvote, please...? An explanation will teach me and the others.
Dor
+3  A: 

No, because jQuery will parse jQuery selectors used in the code, so it will be slower.

SHiNKiROU
Speed wise it should make little difference, especially because of how jQuery is written.
Josh K
@Josh K: you're right that it won't make *much* difference but it will be slower. The question asked if jQuery would make the script faster and more efficient. The answer to that question is no.
Andy E
If you're really worried about the selector there, just don't use a selector: `$(document.getElementsByTagName('input'))...` and it'll work just the same.
Alex Sexton
A: 

If you have a named ancestor element that can help you exclude most of the rest of the web page starting there will greatly speed up your selector.

... tons of html
<div id="radioButtonList">
... the various radio button divs or what nots
</div>
... tons more html

$(function() { 
  $("#radioButtonList :radio:checked").parent().parent().css('background-color', '#FCE6F4'); 
});
Felan