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

Creating a Slider with a Multitude of Images

I am working on a project to develop a gallery that pulls images from a JSON source. I have successfully implemented infinite scrolling to display the images on the first page. However, I am now facing a challenge when it comes to showing the selected imag ...

Vue.js: click event does not trigger transform animation

I am facing a challenge with rotating an arrow icon within a dropdown menu. Despite my efforts, the rotation does not synchronize with the appearance of the dropdown menu. Here is the Vue component code snippet: <nav> <section class= ...

A guide to modifying the color of the Menu component in material-ui

Currently, I am utilizing the Menu component from material-ui and facing an issue while trying to modify the background color. The problem arises when I attempt to apply a color to the Menu, as it ends up altering the entire page's background once the ...

Is it possible to eliminate auxiliary routes in Angular 4?

Recently, I came across an interesting scenario with two <router-outlet> tags, one with a name property. To test this, I set up the following router mapping: export const routing = [ {path:'', pathMatch:'full', component:E ...

Adjust and position any svg element to fit the entire viewport

Forgive me for being just another person to ask this question. Despite my efforts, I have yet to find a solution. I am trying to resize "any" svg to fit the entire viewport, centered. Take for example this svg element: <svg baseProfile="full& ...

A guide to building a versatile dropdown component with Material UI or MUI in a React application

Is there a way to create a reusable dropdown component using Material UI or MUI in React? ...

Setting up node.js for angular - serving static files with connect.static and running unit tests

Currently, I am in the process of setting up a basic node webserver by following a tutorial outlined in Pro AngularJS published by Apress. Node.js along with both the connect and karma modules have been successfully installed on my system. During the ins ...

There appears to be an issue with displaying the graph

I am having trouble understanding how to transfer the values entered in the input to the graph that is displayed successfully. Although the update seems correct, nothing changes when I try to update it and the data remains stagnant. Page.vue <script&g ...

Retrieving JSON data with Node.js

Receiving a JSON response from TMDB: { "id": 283350, "results": [ { "iso_3166_1": "BR", "release_dates": [ { "certification": "12", "iso_639_1": "pt", "note": "Streaming", "release_date": ...

The failure of the Selenium script can be attributed to the presence of the AJAX

Struggling to automate an application with an AJAX loader causing issues? Getting the dreaded error message about element not being clickable when the loader is active? Frustrating, right? But fear not! I have devised a clever solution in the form of a wr ...

Contrasting bracket notation property access with Pick utility in TypeScript

I have a layout similar to this export type CameraProps = Omit<React.HTMLProps<HTMLVideoElement>, "ref"> & { audio?: boolean; audioConstraints?: MediaStreamConstraints["audio"]; mirrored?: boolean; screenshotFormat?: "i ...

What is the most efficient way to dynamically alter the position of a div element within an HTML document using

In a scenario where a parent div contains multiple child divs, it is required that one particular child div named .div_object_last always stays at the end. Below is an example setup : HTML <div class="div_parent"> <div class="div_object"> ...

PHP live data updating: stay current with real-time data updates

I have a functional API that is currently static, but I want it to update periodically and display live data in my HTML code. I'm not sure where to begin. Should I start with Javascript or Ajax? Any guidance would be greatly appreciated. This is my ...

Adding information to a single class that shares a common name

Currently, I have successfully implemented a row cloning scenario where multiple dynamic rows are created after confirming an inventory number from a MySQL database. However, I am facing an issue with inserting the inventory data only to the next DIV eleme ...

Deactivate radio buttons when the table value is greater than or equal to one

On my webpage, there are radio buttons for 'Yes' and 'No'. When 'Yes' is selected, a hidden <div> appears where users can fill in fields. Upon clicking the 'Add' button, the information is displayed in a table. ...

Issue with variable creation within ng-repeat

After reading a question on StackOverflow about determining the number of filtered out elements, I wrote the following code in Angular: <input type="text" ng-model="query" placeholder="Enter query..."> <div ng-if="filteredData.length!=data.length ...

An analysis of Universal Angular.io and Prerender.io from the viewpoint of Googlebot

Currently, my website is set up with Angular 1.4.x and prerender.io, which delivers static cached pages to Googlebot. Googlebot visits each page twice - once by hitting the URL directly, and then again by appending ?_escaped_fragment_ to the URL to access ...

Using jQuery for Dragging and Dropping Elements within Dynamically Loaded Divs with

Is it possible to drag an element on the page into a droppable element inside an ajax loaded div? The code works fine when the droppable element is placed directly in the regular page, but not within the ajax loaded div. It seems like the issue may be rela ...

Issues with PHP and mySQL search functionality

<?php $username = "root"; $password = ""; $hostname = "localhost"; $db_handle = mysql_connect($hostname, $username, $password) or die ("Could not connect to the database"); $selected= mysql_select_db("login", $db_handle); ...

How can I display two slides at once in Ionic 2/3 on a wide screen?

I have been searching for a solution that will allow me to display 1 ion-slide if the device screen is small, but if it's larger, then I want to display 2 ion-slides. Unfortunately, I have not been able to find a suitable solution yet. As an example, ...