Haluk
Haluk

Reputation: 2101

Can I write this javascript more efficiently with jquery?

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

Upvotes: 2

Views: 122

Answers (5)

Felan
Felan

Reputation: 1273

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

Upvotes: 0

Ming-Tang
Ming-Tang

Reputation: 17651

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

Upvotes: 3

Dor
Dor

Reputation: 7484

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/

Upvotes: 0

Nick Craver
Nick Craver

Reputation: 630379

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

Upvotes: 2

Darin Dimitrov
Darin Dimitrov

Reputation: 1038730

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

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

Upvotes: 8

Related Questions