illicITli illicITli - 4 months ago 7
jQuery Question

Why does this ":lt" not work in jquery?

I have figure out the index of the last

p
, it does not work using
$('p:lt(_index)')
. When I replace it with number, it works. Why?



$(function() {
var _index = $('p:last').index();
console.log(_index);
$('p:lt(_index)').css('color', 'red');
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<p>1</p>
<p>12</p>
<p>123</p>
<p>1234</p>
<p>12345</p>
<p>123456</p>
<p>1234567</p>
<p>12345678</p>
<p>123456789</p>
</div>




Answer

You are using the string '_index' as argument of the :lt() pseudo-class, not using the value of the variable. The line:

$('p:lt(_index)').css('color','red');

Should be:

$('p:lt(' + _index + ')').css('color','red');

$(function() {
  var _index = $('p:last').index();
  console.log(_index);
  $('p:lt(' + _index + ')').css('color', 'red');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
  <p>1</p>
  <p>12</p>
  <p>123</p>
  <p>1234</p>
  <p>12345</p>
  <p>123456</p>
  <p>1234567</p>
  <p>12345678</p>
  <p>123456789</p>
</div>