Can I write this javascript more efficiently with jquery?

Do you think jquery can help me make the following script work faster? Thank!

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';
            }
        }       
    }
}

      

+2


source to share


5 answers


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



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

      

+8


source


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



+3


source


You can make this version with jQuery:

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

      

So yes, you can reduce it a bit :)

If you knew which parent you wanted, tell me <span>

, you can do this:

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

      

+2


source


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

0


source


If you have a named predecessor element that can help you exclude most of the rest of the web page, this will speed up your selector significantly.

... 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'); 
});

      

0


source







All Articles