views:

333

answers:

3

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?

+2  A: 
$('#parent').children('#child1').html('html goes here');
Rob Volk
This won't work in a repeater. The ids can't be repeated.
tvanfosson
+2  A: 

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.

<div class="parent">
  <div class="child1"><div>
  <div class="child2">Click Me<div>
</div>

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.

$(function() {
    $('.child2').click( function() {
        $(this).parent().find('.child1').html( 'some html' );
    });
});

The above will add a click handler to each DIV with class child2 and 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.

tvanfosson
Ok.. Can i have this function run at onload()?
ashwnacharya
Yes. Actually, as it it written it will run when the DOM is loaded. That's what the **$(function() { ... });** syntax does.
tvanfosson
A: 

Your question doesn't make a lot of sense. You can just do this:

$("#child1").html("blah");

You don't need a reference to #parent or this.

But assuming that wasn't the case, there are multiple ways you can find an element relative to this:

$(this).children("#child1")

or

$(this).find("#child1") // descendant, not just child

or

$("#child1", this) // descendant, not just child
cletus
This won't work in a repeater. The ids can't be repeated.
tvanfosson