How do I find the last element in .each ()?
I run the following, but I get
(index): 58 Uncaught TypeError: jQuery.last is not a function
var myId;
jQuery.getJSON("https://en.wikipedia.org/w/api.php?action=query&list=embeddedin&eilimit=500&eititle=Template:Infobox&callback=?", {
disablelimitreport: true,
format: "json"
}, function(data) {
jQuery.each(data.query.embeddedin, function(i, item) {
var $this = $(this);
if($this[0] === jQuery.last()[0]) {
var myId = item.pageid;
}
console.log(myId);
});
});
JsFidlle see console
+3
source to share
3 answers
Just enter the length of the element and move the index back. Try it. Hope will work in you.
var myId;
jQuery.getJSON("https://en.wikipedia.org/w/api.php?
action=query&list=embeddedin&eilimit=500&eititle=Template:Infobox&callback=?", {
disablelimitreport: true,
format: "json"
}, function(data) {
jQuery.each(data.query.embeddedin, function(index, item) {
var length = data.query.embeddedin.length;
if (index === (length - 1)) {
var myId = item.pageid;
console.log('The last pageid is : ' + myId);
}
});
});
+4
source to share
If all you want is the last element, you don't need to do .each
across the entire array.
Anything you got after fetching the data can be replaced with one line:
var myId = data.query.embeddedin[data.query.embeddedin.length - 1].pageid
Demonstration:
var myId;
jQuery.getJSON("https://en.wikipedia.org/w/api.php?action=query&list=embeddedin&eilimit=500&eititle=Template:Infobox&callback=?", {
disablelimitreport: true,
format: "json"
}, function(data) {
myId = data.query.embeddedin[data.query.embeddedin.length - 1].pageid
console.log(myId);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
0
source to share