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

When sending strings through an ajax call, spaces are getting converted to "'+'"

In my attempt to utilize AJAX for sending a POST request with multiple strings as parameters, I encountered an issue. The strings I am sending sometimes contain spaces. However, upon receiving the POST on the C# server side, I noticed that the string com ...

My CSS nesting seems to be posing a problem - any idea what

Something unexpected happened while I was working on a project with others. Last night, some files were edited and when I updated my subversion today, the nested divs seemed to have lost their hierarchy. I have been trying all day to fix this issue but wit ...

"Transforming an array using the map method to generate an object containing arrays optimized for

I'm looking to extract an array of objects from a nested array within JS/React. I attempted the following approach, but it resulted in an error regarding react children - indicating that objects cannot be rendered as children and suggesting the use of ...

CSS-only method for creating a fixed position sidebar with adjustable width

https://i.stack.imgur.com/e4Gsv.png I have a vision of creating something similar to the image above solely using CSS. The design must incorporate the following elements: The image-container will hold a 3x4 aspect ratio image, filling the available heig ...

Executing system commands using Groovy is a breeze

One of the scripts I have is a sample.js script that allows me to view files located on the server myHost. It works perfectly: var exec = require('ssh-exec') var v_host = 'myHost' exec('ls -lh', { user: 'username&apo ...

The delivery person is not receiving a reply after making the delivery

When using Express/Node and Postgres with the 'pg' package, the following code snippet is used: const createEvent = (request, response) => { console.log(request.body); const { type, location, current_attendees ...

Unlocking the power of RXJS by de-nesting subscriptions

Trying to resolve the nested subscription issue has become a time-consuming puzzle. I've experimented with mergeMap, flatMap, and switchMap without success. Unfortunately, the examples I've come across don't quite fit my needs, leaving me wi ...

Creating a Dynamic Dropdown Menu in Rails 4

I am attempting to create a dynamic selection menu following this tutorial; however, I am encountering issues as the select statement does not seem to be updating. Below is the code snippet I currently have: #characters_controller.rb def new ...

Developing a personalized Magento2 extension with added support for PWA technologies

Greetings, fellow developers! I find myself at a crossroads when it comes to PWA and custom Magento 2 extensions. As a backend developer for Magento, my knowledge of PWA frontend implementation is lacking. Currently, I am in the process of developing an SE ...

Issue with displaying a vTable component in VueJS / Vuetify

I am struggling with this basic HTML/Vue/Vuetify code snippet below, and I can't seem to get it functioning as intended. const { createApp, computed, ref, reactive } = Vue; const { createVuetify } = Vuetify; const ...

Guide on displaying JSON data from a server on a webpage using Google Charts in real-time

Although I am not a JavaScript developer or an expert in AJAX, I consider myself a novice desktop developer. I would greatly appreciate it if you could guide me on how to connect an MCU that returns JSON data to a web page using Google gauge, running on th ...

Manipulate text with jQuery

Is there a way to remove 'http://' or 'https://' from text using javascript? I am looking for regex solutions as well. This is what I have tried so far: JSFIDDLE HTML: <div class="string"></div> JS: $text = $('.s ...

Can you explain the concepts of 'theme' and 'classes'?

Currently, I am working on a web application using React. I have chosen to incorporate the latest version of Material-UI for designing the user interface. During this process, I came across the demo examples provided by Material-UI (like ) In each demo ...

Switching markdown data into HTML within a Django and React application

I am considering the best way to store blog content in my database so that I can easily display it on an HTML page using an AJAX call. After conducting research, I have found suggestions to store the blog post as markdown, which seems logical since it supp ...

Update the canvas box's color when you interact with it by clicking inside

I'm in the process of developing a reservation system and I'm looking to implement a feature where the color of a Canvas changes when clicked. The goal is for the color to change back to its original state when clicked again. Snippet from my res ...

Can you provide instructions on how to use JavaScript to click and hold a button for a specific duration?

Is it possible to use jQuery to create a button that, when guest button number 1 is clicked, will automatically click and hold down button number 2 for about 3 seconds? I have tried using the mousedown() and click(), but they only register a click, not a ...

Incorporating hyperlinks within the navigation buttons

I'm working on a design where I have six buttons that need to be displayed on top of a background image. How can I ensure that the text inside the buttons stays contained within them? Here is the current code structure I am using, which involves utili ...

Troubleshooting await and async functions in Express.js applications

How can I create an array like the one shown below? [{ "item":"item1", "subitem":[{"subitem1","subitem2"}] },{ "item":"item2", "subitem":[{"subitem3","subitem4&q ...

Encountered an error while executing findByIdAndRemove operation

Could someone please assist in identifying the issue with the mongoose findByIdAndRemove function in the delete route provided below? //DELETE Route app.delete("/blogs/:id", function(req, res){ //Delete blog Blog.findByIdAndRemove(req.params.id, funct ...

Having trouble retrieving the NextAuth session data within Next.js 12 middleware

I've been working on implementing route protection using Next.js 12 middleware function, but I keep encountering an issue where every time I try to access the session, it returns null. This is preventing me from getting the expected results. Can anyon ...