0

Can somebody explain why my elements aren't filtering?

this what wrote in a book, and he sad that if false element will be remove and will displayed elements with true :

$('li').filter(function() { return this.innerHTML.match(/^\d+$/)})

I need to filter only li with 14.15 (i want result just li with 14.15)!

http://jsfiddle.net/crew1251/MYXYX/

<ul id="list">
    <li>raz</li>
    <li>asdf 14.15</li>
    <li>tri</li>
    <li>chetire_Tri</li>
    <li>pyat</li>


</ul>


$('li').filter(function () {
    return this.innerHTML.match(/^\d+$/);
});
1
  • what do you want to filter? Can you write the wanted result with your example. Commented Oct 23, 2013 at 23:36

2 Answers 2

6

If you want to find the lis that contain digits, you should do the following

var listWithDigits = $('li').filter(function () {
    return this.innerHTML.match(/\d+/);
    // return this.innerHTML.match(/\d+$/); // returns lis that end with digits
    // return this.innerHTML.match(/^\d+/); // returns lis that start with digits
    // return this.innerHTML.match(/^\d+$/); // returns lis that contain only digits
});
console.log(listWithDigits.length); // 1

Your current regex is failing because it only accepts lis that contain only digits, because you've wrapped your regex with ^$

http://jsfiddle.net/MYXYX/1/

Sign up to request clarification or add additional context in comments.

6 Comments

doesnt work, i need only 1 result filtered li with digits 14.15
@user1956570 You must have not looked at jsfiddle.net/MYXYX/1 , which I posted, you can see that that it correctly logs the one li with 14.15 in it. Maybe you missed the console.log See jsfiddle.net/MYXYX/2
there must be only li with digits, you have all li
@user1956570 You are doing something wrong, you can see that the result of the call is a jquery object with a single DOM element in it. I really don't know what part you think is not working. Look closer at the fiddle
@user1956570 Dang it dude, are you looking at the jsfiddle I gave you? jsfiddle.net/MYXYX/3 It does not have multiple lis in the filtered jQuery object. Show some code to prove your point (like I did) instead of just saying "it doesn't work"
|
1

You use a wrong pattern, you must remove anchors:

$('li').filter(function () {
    return $(this).html().match(/\d/);
});

Note that you don't need to test more than one digit, thus the + quantifier is useless.

2 Comments

Why are you calling $(this).remove()? OP didn't ask to remove it from the DOM
yeah without remove, just filtered

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.