简体   繁体   中英

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?

if you meant with JQuery it would be something like this (as how i understood your question)

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:

*[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. Online Demo is here .

$(document).ready(function(){
    var total = $("div").length;
    var last  = $("div").eq(total-1).html();
    var secondlast  = $("div").eq(total-2).html();
});

see demo here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM