I have a repeater containing the following HTML snippet:
<div id='parent'>
<div id='child1'/>
<div id='child2'>
<script type="text/javascript" src="script.js"></script>
</div>
</div>
I would like to select the div tagged “parent” using a function inside script.js and set the inner HTML of the div with id “child1”.
My final html should look like this:
<div id='parent'>
<div id='child1'>This inner text was set by jQuery</div>
<div id='child2'>
<script type="text/javascript" src="script.js"></script>
</div>
</div>
How do I do it using jQuery?
First, you can’t code your HTML this way in a repeater. You cannot assign the same ids to multiple elements on the page. Your HTML will need to use classes for identification, if you identify them at all.
Functions in the script tag have no way of knowing where they are in the DOM relative to everything else. You’ll need to tie the function invocation to some element in order to be able to derive the relative DOM relationships to it. The easiest way is to use jQuery (or other framework) to add some handler to the elements.
The above will add a click handler to each DIV with class
child2and when it is clicked, will find it’s parent DIV (note that the class is unnecessary on the parent) and then the correct child whose HTML to update based on its class. Also, note that the above script only needs to be added to the page once, not once per repeater item.