Sarath
Sarath

Reputation: 9146

Jquery selectors optimization

Consider the html

<div id="one" >
<input type="radio" value="x" name="group" >
<input type="radio" value="y" name="group" >
<input type="radio" value="z" name="group" >
</div>

I have two questions regarding the DOM access with Jquery.

  1. Question One

I just want to find the value of input radio which is selected.So i have

Method 1:

var value="";
$("#one input:radio[name=group]").each(function(){
  if($(this).is(:checked)){
   value=$(this).val();
  }
});

Method 2:

var value=$("#one input:radio[name=group]:checked").val();

is there a considerable performance difference in between two methods ? rather than method 2 do that in one line of code..

Or please explain actually what is happening with the line "input:radio[name=group]:checked" inside jquery?

  1. Question Two

I want to set the checked attribute true to input having value "y". So

$("input:radio").filter("[value=y]").attr('checked', true);

and

$("#one input:radio[name=group]").filter("[value=y]").attr('checked', true);

will do the same .

Is there any performance difference in adding "div id" and "[name=group]" ?

Upvotes: 0

Views: 122

Answers (1)

Py.
Py.

Reputation: 3599

When it comes down to pure perf, there is one solution I find better: "Do it yourself" (on jsperf )

I did your test, but it only took me the time to make a copy/paste ;)

http://jsperf.com/selectoroptimization

From the result I add, the best method seems to be the second one for the first question but for the second one it depends on the browser.

Upvotes: 1

Related Questions