view raw
Amete Girl Amete Girl - 1 year ago 39
Javascript Question

Jquery faster way to find a child of an element

I have the following html and I wanted to get the inputs inside the divs

<div id="div1" >
<input class="myinput" value="input inside div1"/>

<div id="div2" >
<input class="myinput" value="input inside div2"/>

To get the inputs I have two approaches the question is which one is preferred.So far I have tried the following two ways. Please suggest which one is better and why Or if there is other best ways of getting the child of an element by class name I am also open.

var input1 = $("#div1 .myinput"); OR
var input1 = $("#div1").find(".myinput");


I created a jsFiddle to compare the performance of both processes and consistently find that $("#div1").find(".myinput"); is more efficient.

This makes sense to me. IIRC, the #div1 .myinput will first find all .myinput elements in the DOM then return only the one with an ancestor of #div1. Whereas, #div1 .find(.myinput) will only find the first #div1 in the DOM then parse it's children, effectively reducing the amount of parsing needed, yielding a more efficient process.

Previous answer prior to question edit:

The fastest way would be to just use:

var input1 = $('#input');

Since ID attributes are supposed to be unique, adding anything else is pointless.