I want to know how to write a jQuery selector to select each of the “input” items below. I do NOT want to select them all at once. These input boxes will not have names or ids. I probably must use some sort of child notation, but I’m not sure how to do it.
<div id="partdiv">
<div class="floater">
<input type="text"/> // Some input box with no id or name
</div>
<div id="descriptiondiv">
<div class="floater">
<input type="text"/> // Some input box with no id or name
</div>
<div id="positiondiv">
<div class="floater">
<input type="text"/> // Some input box with no id or name
</div>
</div>
</div>
</div>
For the first one, for example , I tried:
$("#partdiv > input").bind(....
but that did not work.
There are many different ways to do this – each with different tradeoffs. You can use these selectors:
Or these:
Or these:
Note, that the “proper” way to do this would be to give each input it’s own id or put it in a container that has an id (with no other input tags in the same container). Since neither of those is true, you have to use positional or hierarchy information to discern which input is which.
Which of these different methods to use depends upon how tight or loose you want the relationship between your exact HTML structure and your selectors (e.g. whether the selector still works with certain types of changes to the HTML or not).
The advantage to the first option is that it doesn’t care how many levels/layers of markup there are between the div and the input, only that you’re selecting the first input element in each div. Whereas the third option binds the selector to a very specific HTML implementation and if you put one extra div in between partDiv and the input, it would stop working. The first one would not stop working if you did that so the first and second are much less brittle than the third.
The advantage of the second option is that it’s completely independent of the markup inside of partDiv. The only thing it cares about is the first, second and third input fields in that div.
The main advantage of the third option is that you could rearrange the order of the three input fields and the selectors would still work as long as you maintained uniqueness of the hierarchy specified in the selector.