0

My HTML,

<div id="fullcontainer">
    <div id="a">a</div>
    <div id="b">b</div>
    <div id="c">c</div>
</div>

JS,

   var cache = $('#fullcontainer').children();
   var index = cache.length - 2;
   cache.filter(':lt('+ index +')').remove();

The code that i had given above is working fine as expected, since i have cached the length in a separate variable, But the following code without caching is not working,

   var cache = $('#fullcontainer').children();
   cache.filter(':lt('+ cache.length - 2 +')').remove();

As far as i have learned the expressions at the last level should be evaluated first, But i dont know what is happening with the above piece of codes, Please advice and provide some explanations.

DEMO of the working one, Demo of the non - working one

3 Answers 3

2

Its will work if you enclose cache.length - 2 in brackets like,

cache.filter(':lt('+ (cache.length - 2) +')').remove();

Working Demo

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

3 Comments

But i had given a space outside them.? So spaces are not considered in JS.. Am i right.?
@RajaprabhuAravindasamy, order of operations says that ':lt(' + cache.length happens before the - 2. Spaces don't change the order, but parenthesis do.
Agreed with @zzzzBov. Spaces only provide you better readability. Expressions must be enclosed in brackets not in js but in any language.
2

Your code cache.filter(':lt('+ cache.length - 2 +')').remove(); get evaluated to

cache.filter('NaN)').remove();

it should be

cache.filter(':lt('+ (cache.length - 2) +')').remove();

Comments

2

You need to wrap your value in brackets ( ) to make it evaluated as number:

cache.filter(':lt('+ (cache.length - 2) +')').remove();

Updated Fiddle

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.