views:

329

answers:

3

Is there a way I can get the selected element's parent using only jQuery's/sizzle's CSS selectors?

I need to be able to get an element's parent while using jQuery, but I'm unable use jQuery('#myelement').parent() since I'm receiving the selector as a string and the "user" needs to be able to move back up the tree.

I can't see anything in the docs, so I'm wondering whether it's undocumented or if there's a hack I can use?

A: 

jQuery(jQuery('#myelement').parent()) is getting the object without the additional function.

Ok, end of jokes ;)

I'm guessing that You need the parent selected for the live function and that is why You can't get it this way.

jQuery('#'+jQuery('#myelement').parent().attr('id')).live(something);

It's the way You do it to make it work. If the parent element has no id You can use more complicated tricks

    //newline for reading comfort. skip it. --v
jQuery('[title='+jQuery('#myelement').parent() 
.attr('title',Math.round(Math.random()*100000)+']').attr('title')).live(something);

You can use id or title or class, depends on what is already on the page

And if You really need it to be found by just css selector - as far as I know this is impossible with css selectors by design

naugtur
It *really* needs to be done via a CSS selector as the selector is being passed in as a string. Its rather annoying that CSS can't traverse back up the tree like XPath can. :(
digitala
+2  A: 

Such selector doesn't exists, nor in CSS neither in jQuery/Sizzle.

You can change the source code?

If yes, it is possible to add custom pseudo-selector:

jQuery.expr[":"].getParent = function (node, index, prop, nodes) {
    return jQuery(node).parent(); 
};

Use example (Note that parent already exists, so I've used getParent instead):

jQuery('#myelement:getParent');
Sagi
A: 

Since CSS can't traverse back up the tree like XPath can, I'm doing a bit of munging and checking for the character < in the string, splitting on that and calling .parent() manually. Its not optimal but it's working.

digitala