Juri Juri - 1 year ago 130
jQuery Question

Why gt() and lt() are only jQuery selectors, instead eq() is also a method?

In jQuery, why only

is both a selector (:) and a method (.), instead
are only selectors ("Object doesn't support that property or method")?

Is there a particular reason for this inconsistency/gap of jQuery syntax, that I do not understand?

$("li").eq(1).css("background-color", "yellow");
$("li:eq(1)").css("background-color", "yellow");
$("li").gt(1).css("background-color", "yellow");
$("li:gt(1)").css("background-color", "yellow");
$("li").lt(1).css("background-color", "yellow");
$("li:lt(1)").css("background-color", "yellow");

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="indice">
<li>Primo capitolo</li>
<li>Secondo capitolo
<li>Terzo capitolo</li>
<button id="eq">.eq()</button>
<button id="eq2">:eq()</button><br>
<button id="gt">.gt()</button> <!-- NO -->
<button id="gt2">:gt()</button><br>
<button id="lt">.lt()</button> <!-- NO -->
<button id="lt2">:lt()</button>

Answer Source

It's not considered useful enough to be a built-in, I suppose. Using .eq() instead of :eq allows jQuery to use querySelectorAll for a massive performance improvement.

In any case, you can use .slice like so:

$("li").slice(0,4); // :lt(4)
$("li").slice(5); // :gt(4)

Alternatively, add them yourself:

$.fn.lt = function(n) {return this.slice(0,n);};
$.fn.gt = function(n) {return this.slice(n+1);};


$.fn.lt = function(n) {return this.slice(0,n);};
$.fn.gt = function(n) {return this.slice(n+1);};
$("div").lt(2).css("color", "blue");
$("div").gt(2).css("border", "1px solid red");
$("div").eq(2).css("background-color", "yellow");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download