0

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/

1
  • try whit this if i've understend : return this.id.replace('message_', '') Commented Jul 2, 2012 at 8:40

4 Answers 4

1

Replace your .map function with this:

function() { return this.id.replace('message_', ''); }
Sign up to request clarification or add additional context in comments.

Comments

0

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

0

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

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.