[Javascript] oElement.topParent()
Paul Novitski
paul at juniperwebcraft.com
Fri Dec 9 03:18:11 CST 2011
On Wed, Dec 7, 2011 at 8:59 PM, Troy III Ajnej <trojani2000 at hotmail.com> wrote:
> > What would be your personal definition of a
> > "topParent" property\method of a DOM El?
> >
> > How would you define it?
> >
> > For example: a topParent of Input element
> > would\should be a Form element...
> > But what about other elements including the
> > form element if necessary?
At 12/8/2011 05:50 PM, Mike Dougherty wrote:
>If you are using parent as inspired by the existing .parentNode
>property and top implying the last element in the upward direction
>then I would expect to always end up at document.
...
Troy, I agree with Mike that the desirable target for a topParent
method or property would inevitably vary from one coder to another
and from one application to another, rendering a simplistic
implementation only occasionally useful. Today you might think it's
obvious that an input's topParent should be its form, but tomorrow
you'll need it to be its fieldset or one of the divs that wraps the form.
(I hate to pick on your example because it's really only one
instance, but strictly speaking we don't need a new method to give us
an input control's containing form -- the form property does that
already and isn't being deprecated by the browser makers.)
More versatile than a hard-coded definition of topParent might be an
upward search method that lets the coder specify one or more target
elements using CSS-style selectors, e.g.:
oElement.findAncestor('div.column')
...finds the ancestor div with class "column".
oElement.findAncestor('#content > div')
...finds the ancestor div whose parent is #content.
oElement.findAncestor(array('#content', 'div.column', 'body'))
...returns whichever of the listed elements it finds first
on its ascent through the DOM, in this case going no farther than the
body element.
oElement.findAncestor(array('ul', 'ol', 'dl'))
...finds the parent list structure that contains the given
element. (Not needed when the element is a list item because we can
find the list with parentNode, but handy for elements nested within
list items.)
This functionality resembles jQuery's closest() method but enhanced
with an optional list of targets.
http://api.jquery.com/closest/
Regards,
Paul
__________________________
Paul Novitski
Juniper Webcraft Ltd.
http://juniperwebcraft.com
More information about the Javascript
mailing list