When hovering over various div elements in HTML

I've been experimenting with some code lately, and I'm trying to change the text color of a menu element when hovering over it. I can alter the background color just fine, but for some reason, the text color remains unchanged. Can anyone offer a solution?

<!DOCTYPE html>

<html>
<head>
<title>Untitled</title>
<style type="text/css">
#nav  li {display: inline;}
#nav li  a {color: yellow; text-decoration: none; padding-right: 10px; }
</style>
</head>


<body>
<ul  id="nav">

<li id="a"><a href="#abt">ABOUT </a></li>
<li id="b" ><a href="#sequence">CONTENT</a></li>

</ul>


<div id="abt" onmouseover="chbg('red')" onmouseout="chbg('white')"> 

<p>
Editorial

Hard choices at Copenhagen
During the Climate Change Conference in 2009, the Obama-BASIC meeting was a watershed, saving Copenhagen from a complete collapse and also marking the emergence of the BASIC quartet as a major force i... »
A year later, no lessons learntHard choices at Copenhagen
During the Climate Change Conference in 2009, the Obama-BASIC meeting was a wa...

...

function chbg(color) {
    document.getElementById('a').style.cssText = 'color : black! important';
}

function chbg1(color) {
    document.getElementById('b').style.backgroundColor = color;
}


</script>


</body>
</html>

Thanks

Answer №1

Your code isn't functioning as expected because when you use JavaScript to change the text color of an <li> element, it doesn't automatically apply to the <a> element inside it due to a different color (yellow) being explicitly specified for it. You can try a solution like this:

CSS:

li.hovered a{
 color: black !important;
}

JavaScript:

function chbg(color) {
 document.getElementById('a').classList.add('hovered');
}

or

function chbg(color) {
document.getElementById('a').className+='hovered';
}

Answer №2

Upon reviewing your code, a few things stand out as peculiar. Firstly, it seems that the color argument in your function is not actually utilized.

Additionally, it appears that the element with the id a is a <li>, followed by an <a> element with its own color property. You may want to consider targeting the text color of the element directly using something like this:

function chbg(color) {
    document.getElementById('a').firstChild.style.color = color;
}

Another approach could be utilizing the document.querySelector method instead, to ensure you're selecting the correct element even if there are whitespace nodes present:

function chbg(color) {
    // The CSS selector "#a a" targets the <a> element within the parent <element id="a">
    document.querySelector('#a a').style.color = color;
}

http://jsfiddle.net/xx2fA/

It's also worth noting that the name of the function may be misleading in its current state.

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

Troubleshooting jQuery Dropdown Menu Animation Bugs

Take a look at this interesting fiddle: https://jsfiddle.net/willbeeler/tfm8ohmw/ HTML: <a href="#" class="roll-btn">Press me! Roll me down and up again!</a> <ul class="roll-btns"> <li><a href="#" class="control animated noshow ...

Is it possible for me to route a URL to a particular content generated by Ajax on a separate webpage?

I appreciate anyone taking the time to help with this, especially since I already had to get 12 stitches. Here's what I'm dealing with: mysite.com/documentation - page with a menu and content section (content will load dynamically via Ajax w ...

"Implement a smooth scrolling animation on the page to automatically move a div element upward and lock

I am attempting to create a unique animation for a header div that involves moving it to the top of the screen when the user scrolls down. Once the header div reaches the top, I want it to stay fixed in that position. As the header div moves upwards, it wi ...

Expanding sidebar height to match parent using Flexbox

Looking for the best way to adjust a child element to match the height of its parent? I've experimented with various techniques, but haven't had much success. I'm leaning towards using flexbox as it seems to be the latest trend. Here's ...

The vanishing act of custom fonts in Internet Explorer

This issue with a custom font embed is new to me. I have successfully used custom fonts on many client sites without any problems. One specific client has their own custom font files that are causing trouble. The application in question is embedded in an ...

Can VueJS support multiple v-slots in a component?

I recently set up vee-validate v3.0 for validation in my project and everything was going smoothly until I tried to style my elements. Despite following the documentation on styling and making changes to the vee-validate config, I encountered a new issue - ...

When implementing protractor spyOn() with jQuery's ajax() function, an error is triggered stating 'ajax() method is non-existent'

I am currently testing the functionality of using AJAX to submit a form. Below is the Protractor code for the test: describe('login.php', function() { it("should use ajax on submit", function() { browser.get('/login.php'); spyOn($ ...

inputting an array of strings into the value attribute of an input element using jQuery

Whenever a user writes something in the input field with id="clientAdd" and presses enter, that text should be displayed as a tag inside a div. These tags are then saved as an array of strings, which I want to pass as the value for the hidden input field w ...

Creating models or bulk creating promises in a seed file

When working with a promise chain to add data in JavaScript, I usually start by using Node.js or another method and it works fine (with some variations). However, when attempting to implement this promise chain in a sequelize seed file with the sequelize- ...

Is it possible to use a Proxy-object instead of just an index when changing tabs in material-ui/Tabs?

Using material-ui tabs, I have a function component called OvertimesReport with Fixed Tabs and Full width tabs panel: const TabContainer = ({children, dir}) => ( <Typography component="div" dir={dir} style={{padding: 8 * 3}}> {children} & ...

CSS: choose all elements starting from the n-th element and apply styles to them

Is it possible to choose specific child elements beyond the first few in a parent element? To clarify, let's say there's a div containing 7 spans. How can I select only the spans starting from the 3rd element onwards - so specifically span 4, 5, ...

Having trouble loading AngularJS 2 router

I'm encountering an issue with my Angular 2 project. Directory : - project - dev - api - res - config - script - js - components - blog.components.js ...

Issue with LAMP Stack: HTML table updates are not syncing correctly with the database

Greetings, I am currently working on an HTML form called Index.html <html> <body> <form action="update.php" method="POST"> Department: <input type="text" name="department"><br><br> Subname: <input type="t ...

Discovering nested documents in MongoDB using JavaScript

How to find nested data in MongoDB with the following collection: { "_id": { "$oid": "585b998297f53460d5f760e6" }, "newspaper": { "playerID": "57bffe76b6a70d6e2a3855b7", "playerUsername": "dennis", "player_newspaper": "{\"ID\":\" ...

Encountering error TS2307 while using gulp-typescript with requirejs and configuring multiple path aliases and packages

Currently, I am working on a substantial project that heavily relies on JavaScript. To enhance its functionality, I am considering incorporating TypeScript into the codebase. While things are running smoothly for the most part, I have encountered an issue ...

Enter text into a field on a different webpage and verify if the output matches the expected result

Possible Duplicate: Exploring ways to bypass the same-origin policy I'm facing a scenario where I have a form on my website that requires validation of a number. The validation process involves checking this number against another website where e ...

Sideways movement of a single line within a table

Would you please help with a challenge I'm facing? I want to create a horizontally scrollable row that spans 100% of the page width without overflowing on top of the background image and while keeping the header text in focus. This is what I have att ...

I attempted to use the Stripe API, but it seems to be non

I seem to be encountering an issue with the stripe.customers.create. My goal is to create a new Stripe customer using the email address of the current user, and then update my user with the generated customer.id. Despite the fact that stripe.customers.cre ...

What sorcery does Facebook use to alter the URL without triggering a page reload?

Similar Question: How can I update window location without a reload and # hack? Facebook and Ajax What method does Facebook use to change the URL without reloading the page? In the past, Facebook utilized the hash (#) symbol to prevent the page f ...

Issue: The module '[object Object]' could not be located

const express = require('express'); const app = express(); const jade = require('jade'); const path = require('path'); const server = require('http').createServer(app); const io = require('socket.io').liste ...