Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

$('#parent').children('#child1').html('html goes here');

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top