Adding Multiple CSS Classes to an HTML Element using jQuery's addClass Feature

Take a look at this HTML code snippet:

<html>
<head>
  <style type="text/css">
    tr.Class1
    {
      background-color: Blue;
    }
    .Class2
    {
      background-color: Red;
    }
  </style>
</head>
<body>
  <table>
    <tr id="tr1">
      <td>Row 1</td>
    </tr>
    <tr id="tr2">
      <td>Row 2</td>
    </tr>
  </table>
</body>
</html>

The script section below raises some questions. What will happen when the first row is clicked on? Will it maintain its blue color, or will it change to red? If it stays blue, how can I make it turn red without removing the Class1 class (so that later I can remove the Class2 class and have the row return to its original blue color)?

<script type="text/javascript" language="javascript">

  $(document).ready(function() {
    $("#tr1").addClass("Class1");

    $("tr").click(function() {
      /* When clicked, the selected tr should be highlighted with the Class2 class, while ensuring only one row is selected at any given time */

      $(".Class2").removeClass("Class2");
      $(this).addClass("Class2");
    });
  });

</script>

Update: I experimented with this but encountered unexpected behavior in both FireFox and IE. Can you help identify what might be causing the issue?

Answer №1

When we talk about Cascading Style Sheets, it's important to remember that the newest additions to the properties will always take precedence over the older ones. That's why the color should change to red.

Answer №2

According to information provided by Mozilla on their website here:

In situations where the same property is declared in multiple rules, resolution of conflicts occurs based on specificity first and then with respect to the order of CSS declarations. The arrangement of classes in the class attribute does not play a role.

However, my experience does not align with this explanation.

Answer №3

Give this a shot:

 $("tr").click(function() {
  /* when a tr is clicked, the Class1 class will be toggled on and off to indicate selection, with only one tr being selected at a time */

  $(".Class2").removeClass("Class2");
  $(this).toggleClass("Class1");
  $(this).addClass("Class2");
  $(this).toggleClass("Class1");
});

It's worth trying out to see if it helps address the issue you're facing.

Answer №4

After some investigation, I finally figured it out. It turns out that my example was slightly incorrect. The CSS code actually looked like this:

tr.Class1
{
  background-color: Blue;
}
.Class2
{
  background-color: Red;
}

Therefore, the rule with the most specificity takes precedence, just as explained by Mozilla here:

If the same property is declared in both rules, the conflict is resolved first through specificity, then according to the order of the CSS declarations. The order of classes in the class attribute is not relevant.

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

Press on the row using jQuery

Instead of using link-button in grid-view to display a popup, I modified the code so that when a user clicks on a row, the popup appears. However, after making this change, nothing happens when I click on a row. Any solutions? $(function () { $('[ ...

Unable to Delete Record Using Jquery and Express in 'DELETE' Request

While working on my api using node/express and jquery, I encountered an issue where my DELETE requests are not functioning as expected. JQUERY: $('.formula-body').on('click', function (e) { if (e.target.className == 'fa-trash- ...

Fraudulent emails targeting my posted ads - beware!

Operating a classifieds website where anyone can view and contact posters without needing to be a member poses certain challenges. One of the main issues I face is the abundance of scam emails being sent to users, attempting to deceive them and steal their ...

Compel the browser to initiate a reflow by adjusting the CSS

I am currently in the process of building a responsive image slider without relying on jQuery, using CSS3 transitions. The setup is quite simple: there's a viewport with a UL inside, containing relatively positioned LIs that are left floated. Howeve ...

Stacked column tooltip displaying an array of 3 values

I am working with a json code that looks like this: [[1385420403000,9.86,6.91],[1385506802000,11.89,6.57],[1385593203000,14.11,10.58],[1385679602000,9.1,8.9],[1385766003000,13.59,7.53],[1385852402000,10.68,6.69],[1385938803000,11.03,10.52],[1386025202000, ...

How can I use CSS to position one div on top of another div, without it moving when the page is scrolled down?

I have two images, one rectangle and one circular. The rectangle image needs to be positioned 10em lower due to a banner image at the top. Half of the circle should overlap with the rectangle while the other half remains outside. The center of the circle m ...

Canvas cannot be duplicated due to tainting, html2canvas

I have encountered an issue with my Snapshot button in HTML. Despite trying to add crossorigin="anonymous" to my script, I am still facing the problem of a Tainted Canvas when clicking the button. The button function is as follows: $('#snap').cli ...

Exploring Bootstrap 4: Creating list-inline elements for various screen sizes

Is there a way to align list items on top of each other for a breakpoint <=575px (xs), and align the items next to each other for a breakpoint >575px (sm) using Bootstrap display properties? I found some information on How to display a list inline u ...

Check out the page design for section one!

I have been attempting to create a link to a specific section on a one-page website. Sometimes it works oddly, but most of the time it gets stuck at the section I clicked on and then manual scrolling does not function properly. From what I've researc ...

When the browser size shrinks, turn off the drop-down navigation menu

I'm currently working on a responsive website, and I have encountered an issue with a dropdown menu. When the browser size is reduced to 900px, the menu shifts all the way to the left side. To address this, I added some left padding to keep it off the ...

Creating a "briefing" iframe at the top of a webpage

I'm looking for a way to allow users to embed my iframe at a specific size, like 100x100, and then have it resize dynamically to fit the page size when they click on it. I want this functionality to work regardless of how the HTML embedding the iframe ...

Leveraging CSS and JQuery to manage an iframe with a programmed autoplay feature embedded within

My presentation was created using Adobe Presenter and inserted via an iframe with autoplay enabled upon publication. This means that as soon as the page loads, the presentation begins automatically along with the audio. Since I am unable to disable autopl ...

Utilizing jQuery to accentuate a specific div element when it is positioned directly in the center of the browser window

I have multiple divs with id="scroll_1", "scroll_2", "scroll_3", and so on. I am trying to implement a feature where when any of these divs is in the center of the window, I want to change the background color using jQuery highlight. Currently, I am able t ...

Bootstrap grid button with maximum flexibility

I am currently exploring the intricacies of the bootstrap grid system. My goal is to create a set of buttons that look like this: https://i.sstatic.net/V5meG.png Each button should expand to fill the width and height of its container. However, when a b ...

Fade in elements as the cursor moves, without hovering over a specific element

I'm working on implementing a fade-in effect for content when the mouse moves (similar to Google's homepage), but I'd like to avoid this behavior if the cursor is hovering over a specific div. Here are the basics: $("html").hover(function( ...

Filtering a section of the HTML using Ajax and jQuery

Dealing with an Ajax call in jQuery that's delivering a lot of unexpected HTML content. I'm attempting to extract the specific part I need, but the console is showing an empty string. Can anyone provide guidance on resolving this issue? $.ajax({ ...

checkbox toggling event triggering twice

I have been working on an application that allows users to register for university courses. They can select their registration type, course type, batch, and subjects. The subjects are displayed in a table based on the selected course type and batch. Users ...

I'm looking to extract only two specific keys along with their values from an array stored in a PHP session. I want to transfer this data to a hidden input and then

I have a digital shopping cart where I store selected product data as arrays in session memory. Here is an example of what the arrays look like in the session: Array ( [4] => Array ( [name] => Organic Essential Iodine Supplement ...

Exploring the differences between React state and CSS :hover in the context of a dropdown menu that is accessible to both desktop users (via mouse) and

I have come across a dilemma regarding a dropdown menu that needs to cater to both Desktop/PC users (with mouse) and Mobile devices (with touch). After considering my options, here are the proposed solutions: OPTION 1 One approach is to implement it usi ...

What is the reason for the background image not appearing while utilizing a bootstrap template designed for it?

I recently started working on an asp.net application and decided to integrate a pre-made bootstrap template for the frontend. After some searching, I came across this one. The original site showcasing the template looked really appealing with a background ...