In many cases, I use jQuery’s awesome datepicker in forms. I wanted a generic way to apply it without knowing what the id or class of the input would be. I came up with this:
<span id="datePickerChild">
<input type="text"/>
</span>
<script type="text/javascript">
$(document.getElementById("datePickerChild").firstChild).datepicker();
</script>
Using the mvc3 framework these inputs get put in with their own ids and such at runtime based on the helpers so I wanted this dynamic approach. Is there a more efficient way to be doing this?
Edit:
Using jQuery 1.4.4
That seems like a reasonable approach for this. You could probably do it a little more “idiomatically” with jQuery like the following:
Or even:
One point of confusion, however, is that you say you want to do this without having to know what the id of the element is, although you still use an id in the selector. If you’re trying to use that id “generically” (as in it appears several times on the page), you would want to use a class instead. Once you have a class on the element you need, you would just change your selector to something like: