IDs have better performance, but classes applied to multiple elements
allow you to simplify logic and code.

 <div class="section" id="sectionA">
        <table><tr><td id="row_1">eric 1</td></tr></table>
 </div>
 <div class="section" id="sectionB">
        <table><tr><td id="row_2">eric 2</td></tr></table>
 </div>

 var
     x = $('#row_3'),
     y = x.parents('.section:first');

The same applies to the TR ids, but I don't know the whole context to
propose anything. You could get to any TR using $('.section tr:eq(n)')
without the IDs. See the docs:
docs.jquery.com/Selectors

parents() returns a collection of the parents,
closest() returns the first ancestor that matches OR the element
itself (which in most cases you don't want) if nothing matches.

I prefer using parents with the :first pseudo-selector, so if there
are no matches it returns empty.

On May 19, 3:15 pm, elubin <elu...@yahoo.com> wrote:
> parents() worked, thank you.  also the new closest() worked.  what's
> the exact difference between those two?
>
> why classes instead of ids?  <div class="A"> is better than <div
> id="A">? why?  performance of jquery selectors?
>
> On May 19, 1:53 pm, aquaone <aqua...@gmail.com> wrote:
>
> > A <div> will never be a parent of a <td>. It will be an ancestor but not a
> > direct parent. .parents()
> > <http://docs.jquery.com/Traversing/parents#expr>will look for
> > ancestors.
> > In other news, please use classes on your <div>s instead of pattern matching
> > the id. It's better for a variety of reasons.
>
> > aquaone
>
> > On Tue, May 19, 2009 at 10:46, elubin <elu...@yahoo.com> wrote:
>
> > > I am trying to find the <div> parent of a <td> tag.  In the following
> > > code, I do not understand why the alert shows 0 instead of 1??
>
> > > <script type="text/javascript">
> > > $(function(){
> > >         var x = $('#row_3');
> > >         var y = x.parent('div[id^=idSection_]');
> > >         alert( y.length );
> > > });
> > > </script>
>
> > >  <div id="idSection_A" style="display: block;">
> > >        <table><tr><td id="row_1">eric 1</td></tr></table>
> > >  </div>
> > >  <div id="idSection_B" style="display: block;">
> > >        <table><tr><td id="row_2">eric 2</td></tr></table>
> > >  </div>
> > >  <div id="idSection_C" style="display: block;">
> > >        <table><tr><td id="row_3">eric 3</td></tr></table>
> > >  </div>

Reply via email to