How to apply CSS styling to a specific element using jQuery

When using $(".className"), all elements with the class .className are returned. How can I target a specific element by its index number to apply styling only to that element?

<html>

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head> 
<body>
    <p class="para">first paragraph </p>
    <p class="para">Second paragraph </p>
    <p class="para">Third paragraph </p>
    <script>
        console.log($(".para"));
        // console.log($(".para")[0].css({"color":"red"}));
 </script>
</body>
</html>

Is there a way in this code to set the color of the first paragraph to red and the second paragraph to yellow?

Answer №1

After selecting the element with $(".para")[0], keep in mind that you will receive a DOM element, not a jQuery element. To manipulate its style using jQuery's css method, you must first convert it back to a jQuery element by wrapping it as $($(".para")[0]).

<html>

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head> 
<body>
<p class="para">first paragraph </p>
<p class="para">Second paragraph </p>
<p class="para">Third paragraph </p>
<script>
   
    $($(".para")[0]).css({"color":"red"});
    $($(".para")[1]).css({"color":"yellow"});
 </script>
</body>
</html>

Answer №2

Utilize the power of jQuery .eq() method to target specific elements and manipulate their properties.

https://api.jquery.com/eq/

<html>

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head> 
<body>
<p class="para">first paragraph </p>
<p class="para">Second paragraph </p>
<p class="para">Third paragraph </p>
<script>       
   $(".para").eq(0).css({"color":"red"});
    $(".para").eq(1).css({"color":"yellow"});
    
 </script>
</body>
</html>

Alternatively, you can achieve the same effect with a single command:

$(".para").eq(0).css({"color":"red"}).end().eq(1).css({"color":"yellow"});

Answer №3

Here is an example of how it can be done:

https://example.com/codepen-link

<p id="first-para">First paragraph </p>
<p id="second-para">Second paragraph </p>
<p id="third-para">Third paragraph </p>

$("#first-para").css('color', 'blue');
$("#second-para").css('color', 'green');

Answer №4

To implement changes without an event trigger, you can utilize CSS pseudo-selectors such as first-of-type and nth-child(childIndex)

.para:first-of-type {
  color: red;
}

.para:nth-child(2) {
  color: yellow;
}
.para:nth-child(3) {
  color: green;
}
<p class="para">first paragraph </p>
<p class="para">Second paragraph </p>
<p class="para">Third paragraph </p>

Answer №5

Implement the addClass() function by passing in the index and class name as parameters. Take a look at the code snippet below:

function addClass(index, classname){
  var el = jQuery('.para');
  el[index].classList.add(classname);
  console.log(el[index]);
}
addClass(1, 'active');
.active{
  color:red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<p class="para">first paragraph </p>
<p class="para">Second paragraph </p>
<p class="para">Third paragraph </p>

Answer №6

 $(".para").eq(0).css({"color":"yellow"});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<p class="para">first paragraph </p>`enter code here`
<p class="para">Second paragraph </p>
<p class="para">Third paragraph </p>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implementing a JavaScript validator for an ASP textbox

I have come across many posts discussing how to prevent an ASP textbox from accepting only numbers. However, I am looking for a JavaScript example that can check if the entered value falls between 0 and 100. My validator currently checks if each key entere ...

Is there a way to assign the chosen option from a dropdown list to an input field in Vue 3?

I am working with a list that is returned from an API request. I have a text input field where I can search for items in the list, and the results are displayed dynamically as I type. My goal is to be able to select an option from the list and display the ...

Tips for customizing the appearance of an HTML5 progress bar using JQuery

Here is my method for obtaining the bar: let bar = $('#progressbar'); Styling and animating it is no problem, using either of these methods: bar.css(...) bar.animate(...) However, I am wondering how to adjust the CSS specifically for the prog ...

Using jQuery to loop through a collection

I have a page that displays a list of posts. When a user clicks on the show comments button for a particular post, the comments associated with that post become visible. This functionality is achieved by using this and then searching based on the click loc ...

Can we find a method to incorporate multicolored borders?

I currently have a td element with the following CSS styling: td { border-bottom: 3px solid aqua; } I want to be able to click on these cells and change their color, similar to the images linked below: https://i.sstatic.net/5DscU.png Is there a way ...

Update the image and heading simultaneously when hovering over the parent div

I am looking to enhance the user experience on my website by changing the color of headings and images when a user hovers over a specific section. Currently, I have been able to achieve this effect individually for each element but not simultaneously. Any ...

Using the .slider class on concealed div elements

Explaining this may be a bit tricky, but here we go... I have multiple hidden divs that switch with each other when a link is clicked using $(document).ready(function(){ $('a').click(function () { var divname= this.name; $("#"+divname ...

Top recommendation for utilizing $scope variables in Angular applications

Currently, I am working on a new project and I want to ensure that I am correctly utilizing $scope. After watching an informative video on best practices, Miško mentioned that manipulating $scope properties directly may not be the best approach. Typical ...

The attempt to showcase items in a div element using inline display did not produce

I am having trouble with creating a webpage. I have designed a website but I am struggling to get it right. I have included my HTML and CSS code below. What I am trying to achieve is a header at the top, followed by several sections containing a photo on ...

Should I opt for using plain JavaScript or jQuery when making an AJAX request to fetch JSON data?

As I work on creating a movie app for my personal learning, I am faced with the decision of whether to use raw JavaScript or jQuery for making ajax calls to retrieve JSON data from an API. While it is known that raw JavaScript requires a lengthier process ...

Despite importing jQuery, the variable '$' cannot be located

Whenever I try to click the button labeled test, it doesn't do anything. However, an error message appears in the console debug indicating: Error: Unable to locate variable '$'. I suspect this might be a jQuery issue, even though I' ...

Using React in ES5 to create a button that triggers two separate functions with a

I have encountered an issue with two React classes that both contain a render function returning forms with buttons. In class A, I had to import class B in order to use the form from class B. The problem: Whenever I click the inner button, the outer butto ...

What is the best method to modify and access imported .css files within the WordPress style.css file?

I could use some assistance with a project involving minor edits to a WordPress website. I've hit a roadblock and need some help. The style.css file in WordPress doesn't have much CSS code, but instead imports files like this: /*Animate*/ @impo ...

Displaying errors above the table. Executing ng-repeat in AngularJS

I've been struggling with a seemingly simple issue for hours now. I have a table displaying equipment rows using ng-repeat and input controls, and I want to display validation errors above the table. Here's what I tried: <div class="col-xs- ...

Restricting slash commands in Discord.js to a specific permission level

I'm currently developing a purge command, and I'm struggling to restrict its usage to users with the MANAGE_MESSAGES permission. Below is the source code for the client.on("ready") section as well as the entire command logic. Any assistance on ...

What is the process for including a JavaScript file in an HTML document?

Greetings to all and thank you for taking the time! I have a straightforward query for you.. I have designed an html page featuring only a basemap (open street map). Moreover, I possess a javascript file which utilizes your coordinates to calculate a perce ...

Achieving Center Alignment for Material-UI's <Table> within a <div> using ReactJS

Currently, I am working with a Material-UI's <Table> embedded within a <div>. My goal is to center the <Table> while maintaining a fixed width. I want the table to remain centered in the browser, but if the browser window is minimize ...

Using plain JavaScript (without any additional libraries like jQuery), you can eliminate a class from an element

I'm attempting to locate an element by its class name, and then remove the class from it. My goal is to achieve this using pure JavaScript, without relying on jQuery. Here is my current approach: <script> var changeController = function() { ...

Transfer the index of a for loop to another function

Can you explain how to pass the 'i' value of a for loop to a different function? I want to create a click function that changes the left position of a <ul> element. Each click should use values stored in an array based on their index posi ...

The alert box in Javascript appears before the execution of the statement preceding it

I am encountering a peculiar issue, which is not unexpected considering my limited experience with JavaScript. I am currently working on developing a basic high-low card game where two cards are drawn and the highest card wins. Below you can find the code ...