---
title: "Change color and background via negative index"  
description: "Change color and background via negative index"  
author: "Ethan Karla"  
published: 2021-07-28  
updated: 2023-11-28  
canonical: https://www.mindstick.com/forum/156635/change-color-and-background-via-negative-index  
category: "jquery"  
tags: ["jquery"]  
reading_time: 1 minute  

---

# Change color and background via negative index

How to change [color](https://www.mindstick.com/articles/77/how-to-split-form-background-color-in-c-sharp) and [background](https://www.mindstick.com/articles/65/how-to-change-background-color-of-tab-control-in-c-sharp) via negative [index](https://www.mindstick.com/blog/198/index-in-sql-server) using jQuery eq [method](https://www.mindstick.com/forum/166/webservice-method)?

## Replies

### Reply by Aryan Kumar

\
In jQuery, negative indices are not typically used to directly access elements or properties. However, you can achieve a similar effect by using the **:last** selector in combination with the **prev()** method. Let's say you want to change the color and background of the second-to-last paragraph. Here's an example:

```plaintext
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Change Color and Background with jQuery</title>
  <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
</head>
<body>

  <p>This is the first paragraph.</p>
  <p>This is the second paragraph.</p>
  <p>This is the third paragraph.</p>
  <p>This is the fourth paragraph.</p>

  <script>
    // Using jQuery to select the second-to-last paragraph
    $(document).ready(function(){
      // Selecting the second-to-last paragraph using :last and prev()
      $("p:last").prev().css({
        "color": "white",
        "background-color": "blue"
      });
    });
  </script>

</body>
</html>
```

In this example, **$("p:last").prev()** selects the second-to-last paragraph, and then the **css** method is used to change its color to white and background color to blue. Adjust the selectors and styles based on your specific needs.


---

Original Source: https://www.mindstick.com/forum/156635/change-color-and-background-via-negative-index

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
