This is something that has been troubling me lately, and i've found related questions (like here and here), but they're not quite what i'm looking for and it seems like there should be so i fear i'm missing something.
It is a fairly common pattern (of mine, at least) that an AJAX request returns a snippet of HTML along with a bit of JavaScript that is meant to operate on (or initialize) the HTML in some way. What i'd like to do is to be able to reference the HTML that is being inserted directly from the JavaScript, something like:
<div class="fancy_div">
<select></select>
</div>
<script type="text/javascript">
myAlreadyLoadedLibraryFunction(justInsertedDivAbove);
</script>
But instead my understanding is that the script block is pretty much ignorant of its position on the page, and cannot reference the element directly, but relatively.
What i've seen suggested here is either:
- Apply an id to the div and reference it that way
- With jQuery, use the class to iterate over all divs of that class
For #1, i guess it seems like overkill to generate a unique id to an element that may only need to be referenced relatively going forward.
For #2, it seems like HUGE overkill to iterate over all elements in the page of that class
I am currently in the process of moving away from Prototype and into more jQuery, and so i'm not completely intimate with the jQuery style (but am very interested).
I may be over-thinking this, or missing something, or misguided in my pattern, or just need a nudge - thanks for your time!