views:

13

answers:

1

I wrote a javascript function that uses the innerHtml of a named div (that occurs immediately after the script) for each row as output. the problem is, if I use $('divname'), it always finds the first instance, not the nearest. What's the simplest way in prototype to target the nearest "divname" div?

eg (note, I'm using Grails, hence the <g:...> tags):

<g:each ... >  
  <tr>  
    <td colspan = "4">  
      <g:javascript>  
       ...  
       $('outputdiv').innerHTML = theoutput;  
      </g:javascript>  
      <div id='outputdiv' /> //target THIS instance, not the first!  
    </td>  
  </tr>  
</g:each>
+1  A: 

EDIT: I initially read the question as pertaining to jQuery, but the idea should be the same for Prototype or any other library.

Seems like this is what you want to do:

$('#outputdiv').html(theoutput);

Since IDs must be unique in a document, #outputdiv would be the selector that you want. If you're using outputdiv for multiple IDs, you're not using valid markup and you'll get unpredictable results.

If you need a bunch of outputdivs, you'll want to make it a CSS className, and probably do something with jQuery's closest( ) or nextAll( ) or prevAll( ).

Also, note that your function is going to attempt to set the innerHTML of an element that does not yet exist. You'll probably want to run it onDOMReady or include your script after the element is closed and "ready" in the DOM.

// Assuming theoutput is available in this context
$(document).ready(function(){ $('#outputdiv').html(theoutput) });
ajm
cool. could I forego the "ready" thing if I created the div before the JS?
pennstatephil
Also, just found this: http://stackoverflow.com/questions/2366367/prototype-equivalent-for-jquery-closest-function
pennstatephil
Yes, you could forego "ready" in that case. Basically, you need to make sure your element is part of the DOM before you attempt to query it. Also, I read your $ as being from jQuery, not Prototype. That other SO thread should give you what you need.
ajm