質問
I'm trying to see if there's a way to implement
the "closest" method on phpQuery (just like it works on jQuery).
Is there such a thing?
解決
From Commonly Confused Bits Of jQuery:
CLOSEST(SELECTOR)
This is a bit of a well-kept secret, but very useful. It works like parents(), except that it returns only one parent/ancestor. In my experience, you’ll normally want to check for the existence of one particular element in an element’s ancestry, not a whole bunch of them, so I tend to use this more than parents().
So as parents()
exists in phpQuery you can go with the example from the source
Tip: you can simulate closest() by using parents() and limiting it to one returned element.
$($('#element1').parents('#element2').get(0)).css('background', '#f90');
他のヒント
To actually spell out the phpquery syntax... (took me ages to get this!)
I wanted to extract the 'item' from an RSS feed that contained a specific enclosure (media file link).
function fetch($feed ,$fname)
{
// load the file
phpQuery::newDocumentFileHTML($feed);
// Find the first enclosure that links to the file
// drill up to the parent elements to 'item' take the first (0)
// this is the 'nearest' equivalent
return pq("enclosure[url='" . $fname ."']:first")->parents('item')->xml();
}