Juri Juri - 9 days ago 10
jQuery Question

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

In jQuery, why only

eq()
is both a selector (:) and a method (.), instead
gt()
and
lt()
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?



$("#eq").click(function(){
alert($("li").eq(0).text());
$("li").eq(1).css("background-color", "yellow");
});
$("#eq2").click(function(){
alert($("li:eq(0)").text());
$("li:eq(1)").css("background-color", "yellow");
});
$("#gt").click(function(){
$("li").gt(1).css("background-color", "yellow");
});
$("#gt2").click(function(){
$("li:gt(1)").css("background-color", "yellow");
});
$("#lt").click(function(){
$("li").lt(1).css("background-color", "yellow");
});
$("#lt2").click(function(){
$("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
<ul>
<li>Sottocapitolo</li>
</ul>
</li>
<li>Terzo capitolo</li>
</ul>
<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

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);};

Example:

$.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");
<div>0</div>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Comments