Selector performance to get val() from nested elements
Is there a better more performance way to write this jQuery selector using either jQuery or JavaScript. I'm Mainly looking at selector speed.开发者_开发百科 http://jsperf.com example is a plus.
$('#formEdit div input.t:visible').val();
<div id="formEdit">
<div>
<input class="t" type="text">
<input style="display:none;" class="t" type="text">
<input style="display:none;" class="t" type="text">
</div>
</div>
Some more interesting results based on my testing. I've included the original test and @corroded's tests for convenience. The fastest one uses pure JS.
jsperf link
var form = document.getElementById('formEdit');
var ts = form.getElementsByClassName('t');
var value;
for (var i = 0; i < ts.length; i++) {
if (ts[i].style.display != 'none') {
value = ts[i].value;
break;
}
}
do you have other input.t classes in other forms??
if not just use
$("#formEdit .t:visible").val();
here's a jsperf for you:
link: http://jsperf.com/test-for-so
checked in ff and chrome and mine is still faster
do you have any other .t classes on your whole page?
精彩评论