I am trying to get the ids from some li elements. But I'm not sure how to split the results in the array. So message_1 becomes 1, message_2 becomes 2 and so on.
<ul id="chat_viewport">
<li id="message_1">message</li>
<li id="message_2">message this and that</li>
<li id="message_3">3</li>
<li id="message_4">4</li>
<li id="message_5">5</li>
</ul>
<a href="#" class="test">TEST</a>
$("a.test").click(function(e) {
e.preventDefault();
var idarray = $("#chat_viewport")
.find("li") //Find the li in #chat_viewport
.map(function() { return this.id; }) //Project Ids
.get(); //ToArray
var biggest = Math.max.apply( null, idarray );
alert(idarray);
});
I have an example here http://jsfiddle.net/T5x5d/
4 Answers 4
Replace your .map function with this:
function() { return this.id.replace('message_', ''); }
Comments
If you are sure of the format of IDs, then you can use this:
.map(function() { return this.id.split('_')[1]; })
P.S. Put entire code in question. It is not long and if something happens to your jsFiddle, then other users won't understand the answer.
Comments
modify it to look like this :
$("a.test").click(function(e) {
e.preventDefault();
var idarray = $("#chat_viewport")
.find("li") //Find the li in #chat_viewport
.map(function() { return this.id.split('_')[1]; }) //Project Ids
.get(); //ToArray
var biggest = Math.max.apply( null, idarray );
alert(idarray);
});
Comments
this is a to much but:
$("a.test").click(function(e) {
e.preventDefault();
var idarray = $("#chat_viewport")
.find("li") //Find the li in #chat_viewport
.map(function() {
var match = /(\d+)/.exec(this.id);
return match !== null ? parseInt(match[0]) : 0;
}) //Project Ids
.get(); //ToArray
var biggest = Math.max.apply( null, idarray );
alert(biggest);
});
i dont take to the account that it must have the id of message_ just a number in its id and convert it to a number(if you want to return an array with numbers) if no number was found it will return a 0.
return this.id.replace('message_', '')