[英]Get x number of last element
How to effectively get a certain number of elements from the end? 如何从头到尾有效地获取一定数量的元素?
<div><span>1</span></div>
<div><div>looks like 2</div></div>
<div>three!!</div>
For example, how would I fetch the contents last 2 div
s? 例如,如何获取最近2个
div
的内容?
if you meant with JQuery it would be something like this (as how i understood your question) 如果您的意思是与JQuery,它将是这样的(因为我如何理解您的问题)
var last = 5;
jQuery('body> div:nth-last-child('+(last+1)+') ~div')
If you're looking for an xpath query - which you can use both in Javascript or PHP: 如果您正在寻找一个xpath查询-您可以在Javascript或PHP中使用它们:
*[position() > last() - 2]
You execute it relative to the context-node which is the parent here: 您相对于上下文节点(即父节点)执行它:
$doc = new DOMDocument();
$doc->loadXML($xml);
$context = $doc->documentElement;
$xp = new DOMXPath($doc);
$elements = $xp->query('*[position() > last() - 2]', $context);
var_dump($elements->length);
foreach($elements as $i => $element) {
printf("%d: %s\n", $i, $doc->saveXML($element));
}
Output: 输出:
int(2)
0: <div>
<div>looks like 2</div>
</div>
1: <div>three!!</div>
Hope this helps. 希望这可以帮助。 I took the right to beautify the XML.
我有权美化XML。 Online Demo is here .
在线演示在这里 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.