Why does the JavaScript background color change take precedence over CSS selectors for my object?

Can someone explain why my list elements are not turning blue when I hover over them, even with the CSS and JS provided below?

li { background:red; }
li:hover { background:blue; }

Here is the JS I am using:

document.getElementsByTagName("li")[0].style.backgroundColor="yellow";

I've tested this on both Chrome and FF and still no luck. Check out the example here: http://jsfiddle.net/42bQr/. Any suggestions on why this is happening?

Answer №1

The reason behind this phenomenon is the heightened specificity of inline styles. To counteract inline styles, you can utilize the following override:

li:hover { background:blue !important; }

Answer №2

The reason for this behavior is due to the use of "inline" style, which takes precedence over other styles.

To better understand what's going on, take a look at this demonstration: http://example.com

When running the demonstration, you'll notice the following output:


    <div class="blue-bg" style="background-color: green;">hi</div>

Answer №3

The reason behind this behavior is due to setting the style as an inline style, which holds the highest level of specificity. When a list item is clicked on, it will appear as:

<li style="background-color: yellow;">My List Element 1</li>

The order of specificity for selectors is as follows:

  • Universal selectors
  • Type selectors
  • Class selectors
  • Attributes selectors
  • Pseudo-classes
  • ID selectors
  • Inline style

To work around this issue, you can assign a class to the list item using the following method:

var listEls = document.getElementsByTagName("li");
for (var i = 0; i <= listEls.length - 1; i++) {
    listEls[i].onclick = function () {
        this.className = 'yellow'
    };
}

where

.yellow {
    background:yellow;
}

View Example on jsFiddle

Answer №4

The reason for this issue is the inline style you have applied to your selector with higher specificity.

Check out this Fiddle

li:hover { background:blue; !important}

If you prefer using Javascript, you can utilize the Element ClassList API. However, this API is only supported in major browsers. Refer to the Browser Compatibility Matrix before implementing. Here is a sample code snippet:

Javascript

var listEls = document.getElementsByTagName("li");

function addYellowClass() {
  this.classList.add('bg-yellow');
}

for (var i = 0; i <= listEls.length - 1; i++) {
  listEls[i].onclick = addYellowClass;
}

JSBIN Example

Answer №5

Just like what has been mentioned by others, the inline style always takes precedence when clicked. To achieve the desired effect, you might consider implementing a hover/mouseover event to add a class such as $(this).addClass('blueBG') that sets the background color to blue, and then remove it on mouseout.

Answer №6

When it comes to CSS styling, remember that "background-color" holds more weight than "background." This means that your JavaScript code will override both CSS properties if it is more specific.

To avoid conflicts, consider using "background-color" as a property in both your CSS and JavaScript.

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

"Attempting to use push inside an if statement does not function as expected

The code snippet provided is causing an issue where `items.push` is not functioning correctly within the `if` statement. Interestingly, if you uncomment the line just before the closing brace `}`, then `items.push` works as intended. for (i = 0; i < ...

Is there a way to keep a label in a Material-UI TextField from getting obscured by an adornment when the input is not in focus?

Here is the code for my custom TextField component: <TextField fullWidth: true, classes, helperText: errorText, FormHelperTextProps: getInputProps({ error }), InputProps: getInputProps({ error, endAdornment: error ? <Warning ...

Dynamic content displayed within adjacent div elements

I am currently working on a project where I am dynamically generating an outline by creating panels and labels in ASP.NET. Each node in the outline is defined by an outline number and outline text, which are obtained from a database that defines the relati ...

Altering Collada texture information during the loading process of the .jpg file

Is there a way to modify the texture image data, such as changing the .jpg header text, when loading the .jpg texture in three.js? I am curious if the texture data is accessible somewhere within the code, possibly as a string. How could I go about this? ...

Perform the same actions on every element within the ul li

I'm facing an issue with my unordered list, where each list item contains a span element with an image inside. My goal is to set the background-image of each span to be the same as the image it contains, while also setting the opacity of the image to ...

Retrieving Text Between HTML Tags Using jQuery

Disclosure: I am fully aware of the messy HTML code in this legacy application. Unfortunately, due to its extensive dependencies, making any changes to the HTML structure is not feasible. Despite the circumstances, here is the code snippet at hand: <t ...

Combining various array values into a single key in JSON格式

Issue: I am working on a sign-up form for new users using HTML. The goal is to store multiple arrays (each containing "username: username, password: password, topScore: 0) within one JSON key ("user" key). However, the current functionality only allows f ...

Extracting JSON Value from a Script Tag

Seeking a more efficient method to extract the designated JSON value (highlighted in yellow) that is currently acquired using the code below. Although effective, it lacks efficiency. $("head > script:nth-child(55)").text().trim().replace(" ...

How come it is not possible for me to choose all elements containing an attribute value saved in a variable?

Imagine you have the following snippet of HTML code: <div data-id=5>...</div> <img data-id=5 src=...> <input data-id=5 ...> ... Your task is to select and remove all elements with the attribute data-id set to 5. Here is one attemp ...

Check if array2 is partially ordered as array1 in JavaScript

Is there a more efficient way to achieve these conditions in JavaScript using vanilla or lodash? const array1 = [1, 2] const array2 = [1, 2, 3, 4] //true const array2 = [1, 3, 2, 4] //true const array2 = [4, 3, 2, 1] //false const array2 = [2, 3, 1, 4] / ...

The functionality of clicking on a jQuery-generated element seems to be malfunctioning

When using Jquery, I am able to create an element and assign it the class .book: jQuery('<div/>', { name: "my name", class: 'book', text: 'Bookmark', }).appendTo('body'); I then wanted to add funct ...

Retrieving data from a <span> element within a webpage created using ReactJS

I am completely new to the world of web design and development, so there may be some mistakes in my request. Essentially, I have a webpage that contains numerous span tags like the following example: These span tags are part of a significantly large DOM t ...

I am encountering challenges with React.js implemented in Typescript

Currently, I'm grappling with a challenge while establishing a design system in ReactJS utilizing TypeScript. The issue at hand pertains to correctly passing and returning types for my components. To address this, here are the steps I've taken so ...

Difficulty arises when applying hover effects to animations using callbacks

Currently facing an issue with the hover event in jQuery. There are two side-by-side containers with hover events on both. When hovering, a div containing additional information slides up into view and slides back down when the hover ends. The concept is ...

Creating an Image Link within Nivo Slider

I have been trying to figure out how to make an image a link in NivoSlider. I know that I can use captions to create a link, but I want the actual image to be clickable for better accessibility. I found a similar question on StackOverflow, but it was rela ...

The AngularJS ng-if directive is failing to function properly, despite the logged boolean accurately reflecting the

I created a custom directive that handles the visibility of text elements on a webpage. While this logic works correctly half of the time, it fails the other half of the time. Here is the code snippet from my directive: newco.directive 'heroHeadline& ...

Getting the Firebase Project Name or ID from a Cloud Function is a simple task that involves using

While working with Cloud Functions, I need to retrieve the project name from one of my Javascript server files. The project name is stored in .firebaserc file, but I am not sure if this file is accessible on the server side. Is there a way to achieve somet ...

CSS KeyFrame animations

My goal is to have my elements gracefully fade in with 2 lines extending out of a circle, one to the left and one to the right. However, I am struggling to achieve this. Every time I attempt to display the lines, it ends up shrinking the entire design. M ...

Tips for reducing code length in jQuery

Here's an interesting question that I've been pondering. Is there a more efficient way to optimize and condense code like the one below? Could it be achieved using functions or loops instead of having lengthy jQuery code? var panels = ["panel1", ...

push one element to fit in between two adjacent elements

Is there a way to make my responsive webpage ensure that the full-screen element appears between sibling elements when viewed on mobile devices? Check it out on desktop or on mobile here. I have three (div) elements: two in one row and another in a separa ...