Reputation: 9146
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.
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?
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
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