jQuery slice()
by negative index
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("p").slice(-3).css("background-color", "yellow"); });/*ww w. ja v a 2 s . c om*/ </script> </head> <body> <h1>Welcome to My Homepage</h1> <p>This is a test (index 0).</p> <p>CSS (index 1).</p> <p>I am from java2s.com (index 2).</p> <p>This is another test (index 3).</p> <p>And I'm in love with Daisy (index 4).</p> <div>We use a negative number (-3), which selects the three last p elements. This will start the selection of p elements from the p element with index position 2 (the 3rd element from the end).</div> </body> </html>