JavaScript and modifying the attributes of the nth child

I'm working on a navigation bar that changes the "background-image" of menu items using the nth-of-type CSS selector. Now, I need to figure out how to dynamically change the picture of the "background-image" when hovering over a specific menu item using Javascript.

<html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Islington College - Home</title>
        <link rel="stylesheet" href="css/style.css" type="text/css">
        <style type="text/css">      
            nav ul li:nth-of-type(1){
                background-image: url('images/navigation/active_home.png');
                background-size: 40%;
                background-repeat: no-repeat;
                background-position: center top;
            }
            nav ul li:nth-of-type(2){
                background-image: url('images/navigation/courses.png');
                background-size: 40%;
                background-repeat: no-repeat;
                background-position: center top;
            }
            nav ul li:nth-of-type(3){
                background-image: url('images/navigation/lectures.png');
                background-size: 40%;
                background-repeat: no-repeat;
                background-position: center top;
            }
            nav ul li:nth-of-type(4){
                background-image: url('images/navigation/admission.png');
                background-size: 40%;
                background-repeat: no-repeat;
                background-position: center top;
            }
            nav ul li:nth-of-type(5){
                background-image: url('images/navigation/facilities.png');
                background-size: 40%;
                background-repeat: no-repeat;
                background-position: center top;
            }
            nav ul li:nth-of-type(6){
                background-image: url('images/navigation/contact.png');
                background-size: 40%;
                background-repeat: no-repeat;
                background-position: center top;
            }
        </style>
    </head>
    <body>
    <header class="main_header">
            <figure id="logo">
                <img src="images/logo.png" alt="Islington College Logo">
            </figure> 
            <nav>
                <ul>
                    <li><a href="index.html" style="color: #EE2B32; padding-top: 43px;">Home</a></li>
                    <li><a href="courses.html" style="padding-top: 40px;">Courses</a></li>
                    <li><a href="lectures.html" style="padding-top: 40px;">Lectures</a></li>
                    <li><a href="admission.html" style="padding-top: 34px;">Admission</a></li>
                    <li><a href="facilities.html" style="padding-top: 38px;">Facilities</a></li>
                    <li><a href="contact.html" style="padding-top: 41px;">Contact</a></li>
</ul>
            </nav>
    </header>

Answer №1

What is the reason for using JavaScript in this scenario? You could achieve the same result with CSS:

nav ul li {
    background-size: 40%;
    background-repeat: no-repeat;
    background-position: center top;
}

nav ul li:nth-of-type(1){
    background-image: url('images/navigation/active_home.png');
}
/* Here's an example */
nav ul li:nth-of-type(1):hover {
    background-image: url('images/navigation/active_home_hover.png');
}

nav ul li:nth-of-type(2){
    background-image: url('images/navigation/courses.png');
}
nav ul li:nth-of-type(3){
    background-image: url('images/navigation/lectures.png');
}
nav ul li:nth-of-type(4){
    background-image: url('images/navigation/admission.png');
}
nav ul li:nth-of-type(5){
    background-image: url('images/navigation/facilities.png');
}
nav ul li:nth-of-type(6){
    background-image: url('images/navigation/contact.png');
}

Answer №2

Vanilla JavaScript Approach:

const firstListItem = document.querySelectorAll('ul li:nth-child(1)');
firstListItem.style.backgroundImage = "url('newbg.png')";

Using jQuery:

$( "ul li:nth-child(1)" ).css("backgroundImage", "url(newbg.png) no-repeat");

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

Printing dynamic data

When the print button is clicked, I need to print dynamically generated data from a table that has an ID. The table data (td and tr) is dynamically generated. I have successfully retrieved the table data and attempted to print everything using window.prin ...

The default value in an Ionic select dropdown remains hidden until it is clicked for the first time

Having an issue with my ion-select in Ionic version 6. I have successfully pre-selected a value when the page loads, but it doesn't show up in the UI until after clicking the select (as shown in pic 2). I'm loading the data in the ionViewWillEnt ...

Obtain Value from Function Parameter

In my Angular project, I have a function that is called when a button is clicked and it receives a value as an argument. For example: <button (click)="callFoo(bar)">Click Me!</button> The TypeScript code for this function looks like ...

What is the best way to maintain the toggleClass event state once an ajax call has been made?

If I have the HTML code below <div class="row"> <div class="link grey"> <a href="#">Link</a> </div> </div> <div class="row"> <div class="link"> <a href="#">Link</a> </div> & ...

The system encountered a TypeError: Unable to access the 'nativeElement' property as it is undefined

Hello, I am a beginner in Angular 2 and currently working on an image cropping plugin. My goal is to display the image on a canvas element. Below is my HTML code: <div class="row"> <div class="col-sm-6"> <canvas id="layout" width="40 ...

"Implementing a 960 Grid System with an HTML5 Header Element

Exploring 960.gs and HTML5 as a beginner has led to some challenges. My current project involves an image spanning 2 grid units, followed by a div taking up 5 units on the same line, with a line break needed before displaying a heading. I attempted the la ...

The markers within a loop in react-native-maps are failing to render

Recently, I've been delving into the world of React Native app development for iOS. Specifically, I've been experimenting with the react-native-maps package. Here's the issue I'm facing: When I statically render a single MapView.Marker, ...

Strange Actions with JQuery Drag-and-Drop Functionality

Apologies for my limited experience with JQuery UI, but I am in the process of creating a web-based chess engine for 2 players using JavaScript. Instead of point and click, I have decided to implement a user-friendly drag and drop feature for non-mobile us ...

Receiving a JSON object in response after sending data to a server using JavaScript

I am facing an issue with passing an email and password on login click to a database using PHP. After testing the email and password combination, PHP sends back a JSON object. While I have verified that the PHP code is functioning correctly and returns a J ...

Can you explain the meaning of `<%= something %>` to me?

I've been working on a javascript project and I'm curious about the purpose of surrounding a variable with this syntax? <%= variable %> I attempted to research it myself but didn't come across any helpful information, so my apologies ...

"I am trying to figure out how to set a link to an image using JavaScript. Can someone help me

I need help figuring out how to insert an image or gif file within two inverted commas '' in this line of code: _("status").innerHTML = ''; (line number 13 in the actual code) Your assistance with this question would be greatly appreci ...

JSON API WebConnector for Tableau

After creating a tableau webconnector to extract data from an internal API, I used earthquakeUSGS.html as a reference (https://github.com/tableau/webdataconnector). The API responds with json data (see code below). Utilizing the "Web data connector simulat ...

Does anyone have an idea of the origin of the item in this ajax .each function?

Currently, I am utilizing the Etsy API with JavaScript by calling this AJAX code: $.ajax({ url: etsyURL, dataType: 'jsonp', success: function(data) { This code returns an object array, if I'm not mistaken. It then proceeds to enter this . ...

Fetch request encountered a 500 error due to the absence of the 'Access-Control-Allow-Origin' header on the requested resource

Currently, I am in the process of developing a front-end web application using create-react-app and need to make a request to the ProPublica API. The fetch call code snippet is as follows: export const fetchSenators = () => dispatch => { fetch(' ...

Nextjs - resolving the issue of shopping carts displaying incorrect total amounts

I am currently facing an issue with the total cart amount while building a shopping cart. The problem arises when I visit the cart page as it only displays the amount of the last item added to the cart. state = { cart: { items: [], total: 0 }, }; ad ...

Infinite loop readiness with JQuery

My current project involves preloading images and seamlessly fading them in once they are fully loaded using JQuery. To achieve this, I attempted to create an invisible image tag where the images would load before setting the source back to the original im ...

React search filter feature with dropdown selection

After successfully implementing a search filter in my React app, I encountered an issue when trying to incorporate a select tag to change the search filter criteria. class BookList extends Component { state = { search: '', selectedValue: ' ...

Difficulty with Horizontal Mousewheel Scrolling

Struggling to implement a horizontal scrolling feature (via mousewheel) for both containers in the code below. I want this feature to be easily applied to any future container creations as well. <body> <style> #container { display: flex ...

Utilizing JSON for HTML conversion in Codeigniter

public function getCrew(){ $search = $this->input->post('name'); if($this->input->post('ajax') && (!empty($search))){ $result = $this->model->getNames($search); foreach($result as $r){ ...

Looking to verify a disabled select element and adjust the opacity of that element when it is disabled

$_product = $this->getProduct(); $_attributes = Mage::helper('core')->decorateArray($this->getAllowAttributes()); ?> <?php if ($_product->isSaleable() && count($_attributes)):?> <dl> <?php foreach($_attrib ...