Having trouble applying CSS styles to an element using JavaScript

Hello, I have an unordered list with some list elements and I am trying to apply a CSS style to highlight the selected list element. However, the style is not taking effect as expected.


function HighlightSelectedElement(ctrl) {
    var list = document.getElementById("myslidemenu").getElementsByTagName('li');

    for (i = 0; i < list.length; i++) {
        list[i].style.color = "blue";
    }

    ctrl.style.color = 'white';
}

Here is how my HTML structure looks:

<div id="myslidemenu" class="jqueryslidemenu">
    <ul>
        <li onclick="HighlightSelectedElement(this);"><a href="Dashboard.aspx">Dashboard</a>
        </li>
        <li onclick="HighlightSelectedElement(this);"><a href="Geofence.aspx">Geofence</a>
        </li>
        <li onclick="HighlightSelectedElement(this);"><a href="Personnel.aspx">Personnel</a>
        </li>
    </ul>
    <br style="clear: left" />
</div>

The parent div tag contains another inner div tag. Is there a way to override the inner div tag and make changes to the selected list item in the ul?

My CSS code is structured like this:

.jqueryslidemenu ul li a:hover{
     background: black; /*tab link background during hover state*/
     color: Yellow;
  }
.jqueryslidemenu{
     font: bold 12px Arial;
     background: #414141;
     width: 100%;
}
.jqueryslidemenu ul{
     margin: 0;
     padding: 0;
     list-style-type: none;
}
/*Top level list items*/
.jqueryslidemenu ul li{
     position: relative;
     display: inline;
     float: left;
}
/*Top level menu link items style*/
.jqueryslidemenu ul li a{
     display: block;
     background: #414141; /*background of tabs (default state)*/
     color: white;
     padding: 8px 10px;
     border-right: 1px solid #778;
     color: #2d2b2b;
     text-decoration: none;
     height: 1%;
}

Answer №1

To achieve the desired effect, focus on modifying the appearance of the <a> element rather than the <li> element. Although the style of the <li> has been successfully updated, the <a> retains its original styling which requires JavaScript to override.

Answer №2

Is your goal to update the background instead? Like this?

I have excluded the anchors in the test to avoid any 404 errors.

function MakeSelection(element) {                         
    var menuList = document.getElementById("myslidemenu").getElementsByTagName('li');

    for (index = 0; index < menuList.length; index++) {
        menuList[index].style.background = 'blue';
    }

    element.style.background = 'white';
}

Answer №3

Your current approach is not effective because the page is constantly refreshing.

For instance, when you click on a link, the browser redirects you to that particular destination.

To address this issue, you can check the current page after it loads and identify the corresponding link in your menu, then apply CSS styling to it.

Incorporate this script into your webpage:

    $(document).ready(function () {
        var page = top.location.toString().split("/");
        alert(page[page.length - 1].toString());
        $('#myslidemenu li').css('color', 'blue');
        $('#myslidemenu').find('a[href="' + page[page.length - 1].toString() + '"]').closest('li').css('color', 'white');

    });

Upon document ready, this script captures the page name, locates the anchor tag with href matching the current page, and changes the color of its closest list item.

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

Easily transfer files without the need to refresh the page by utilizing the power of AJAX

In my page file-upload.jsp, I have the following code snippet: <form action="" id="frmupload" name="frmupload" method="post" enctype="multipart/form-data"> <input type="file" id="upload_file" name="upload_file" multiple="" /> <in ...

Enhance the progression bar using JavaScript

Is there a way to dynamically update a progress bar in HTML while a function is running? function fillProgressBar() { var totalIterations = 100; for (var i = 1; i <= totalIterations; i++) { //perform calculations progressBarWidth = (i/to ...

Ways to dynamically eliminate focus around text inputs

I have created an HTML page and here is the link to it: My main goal is to remove the black border around the text input on this page. The challenge I am facing is that the 'things to do' list is generated dynamically, meaning it is empty when t ...

Utilizing a responsive design with a bootstrap grid system, featuring expandable columns for

After creating a bootstrap grid page, I am facing an issue with the layout on mobile screens. My problem arises when trying to reorder the cards properly for mobile view. Here is my current logic: <div class="row"> <div *ngFor="let col of [1, ...

Error encountered when generating bower.json due to absence of version number

After generating the bower.json file, I noticed that the version number was not included in the information collected. The current content is as follows: { "Name": "conFusion", "Authors": [ "Aurora" ], ... } Although the version n ...

Customizing blockquote styling in QuillJS with a unique class

Currently, I am exploring a method to include a custom class when the user selects the blockquote toolbar button. When the blockquote is clicked, it generates the following element: <blockquote class="ql-align-justify">this is my quoted tex ...

Ways to create distance between repeated cards in a loop. My method involves utilizing ajax, jquery, and bootstrap

view image description here What is the best way to create some space between these closely aligned cards? .done((todos) => { todos.forEach(el => { console.log(el) $("#todo-list").append(` <d ...

The second request made with $.ajax is bypassed

I have been working on integrating the Google Maps JavaScript API and attempting to update a heat map when a user clicks on a specific div element. The latitude and longitude data used for the heatmap are fetched from local JSON files. While I have success ...

Transmit the data.json file to a node.js server using Postman

Hi there, I have a file named data.json saved on my desktop that I want to send to a node.js function. The contents of my data.json file are structured as follows: [{"key":"value"}, {same key value structure for 8000 entries}] This fil ...

Use the useEffect hook to pass newly updated data to a FlatList component

I have encountered an issue with updating a FlatList component in my React Native application. The scenario involves running a graphql query to render items and then refetching the data when a mutation is executed using Apollo's refetch option. Althou ...

What is the best way to transfer the http server variable between different layers in node.js without requiring it in a separate file?

I've developed a nodeJS application that involves creating a server in the file server.js. The code looks like this: http.createServer(app).listen(app.get('port'), function (err) { if (err) { console.error(err); } else { ...

Enhancing React Native experience by dynamically editing array elements

This code block defines the state of my program, including an array: this.state = { arr: [{ arrid: 0, arrEmail: '', arrName: '', arrPhone: '' }], id: 0, email: "", isChecked: true, name: "", phon ...

Best practices for utilizing the getTile() method within Google Maps

I have a question about storing markers in a database using tile IDs. The goal is to display all the markers associated with a specific tile when it is displayed on a map. Initially, I created a code that was not working correctly. It only requested one ...

Other options to consider besides using flex wrapping

Is it possible to use other methods to wrap these image items with the display: flex; property besides using the flex-wrap property? Are there alternative approaches available? body { margin: 0px; } img {} h1 {} p {} a { background-color: #ddd; ...

Getting HTML from Next.js middleware - a step-by-step guide

Is there a way to send the HTTP Status Code 410 (gone) together with a customized HTML message? I want to display the following content: <h1>Error 410</h1> <h2>Permanently deleted or Gone</h2> <p>This page is not foun ...

Utilize a fluid AJAX endpoint for the Vue Select2 encapsulated component

I have customized the Wrapper Component Example based on VueJS documentation by adding the AJAX data source feature. You can view my modified code here. My goal is to dynamically set the ajax url property of my select2 component, like this: <select2 :o ...

Effortless Sidebar Navigation for populating primary content

Initially, I must confess that even though this seems like a straightforward issue, I am just as puzzled as you are by my inability to solve it independently. With no prior experience in web development, I find myself in need of using GitHub Pages to docum ...

Testing a React component's function within the confines of a Redux Provider component

My current challenge involves unit-testing a React component called TodoList. This component essentially maps through items and displays them in the render method. These items, of type TodoItem, are retrieved from the Redux store using MapStateToProps. Be ...

Cannot get the before-leave transition JavaScript hook to function properly in Vue.js

I am facing an issue with my variable, transitionName, in the beforeLeaveHook function. Despite attempting to change it to 'left', the value remains stuck at 'right'. Any assistance on resolving this matter would be greatly appreciated. ...

Is there a way to modify the response code that has already been dispatched?

I wrote this code with the intention of sending response headers quickly: const http = require('http'); const fs = require('fs'); const server = http.createServer((req, res) => { fs.readFile(/*file path*/, 'utf8', (err, ...