Difficulties encountered while attempting to modify a class using Javascript

Recently, I've encountered an issue with my JavaScript where I am unable to keep a particular element's class changed. Despite attempting to change the class to "overlist", it only stays that way briefly before switching back to its original state, underlist. I'm really struggling to find a solution to make the class stick.

My HTML code:

<ul class="overlist">
    <li>
        <a onClick="activateTutorials()">Tutorials</a>
        <ul class="underlist Tutorials">
            <li>
                <a href="#" onClick="frame(1)">Filler Text</a>
            </li>
            <li>
                <a href="#" onClick="frame(2)">More Filler Text</a>
            </li>
            <li>
                <a href="#" onClick="frame(3)">Foo Tutorial</a>
            </li>
            <li>
                <a href="#" onClick="frame(4)">More foo Tutorial</a>
            </li>
            <li>
                <a href="#" onClick="frame(5)">Foo Guide</a>
            </li>
        </ul>
    </li>

CSS code:

.underlist {
    display: none;
}

Javascript code:

function activateTutorials(){

    if(document.getElementsByClassName('Tutorials').classList.contains('underlist')){

        document.getElementsByClassName('Tutorials').classList.remove('underlist');

    }else{

         document.getElementsByClassName('Tutorials').classList.add('underlist');

    }
};

Answer №1

Here are some tips for debugging: Firstly, make sure to check if the function is actually running (it wasn't for me). I made a slight modification:

<a href="#" onClick="javascript:activateTutorials();" class="Tutorials">Tutorials</a>

Secondly, remember that getElementsByClassName returns an array, so adjust your script accordingly:

function activateTutorials(){
console.log(document.getElementsByClassName('Tutorials'));
    if(document.getElementsByClassName('Tutorials')[0].classList.contains('underlist'))
 {
     document.getElementsByClassName('Tutorials')[0].classList.remove('underlist');
 }else{
     document.getElementsByClassName('Tutorials')[0].classList.add('underlist');
 }
};

If you see a console statement at the beginning of your function, it's a helpful tool for debugging (in Chrome, access it with Ctrl+Shift+J).

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

Navigating through multiple pages with React Native stack navigation

I'm currently in the process of developing a react native app and I'm facing some confusion with regards to page navigation. It appears that there is a glitch in the navigation flow, causing it to skip a page. <NavigationContainer> ...

Unique design and elements featuring the `width: auto` property for custom fonts

In my current project, I am utilizing the popular 'Open Sans' font family. However, I am encountering a specific issue. The problem arises with buttons and other elements that have width: auto. Upon page load, these elements initially have their ...

Why am I encountering difficulties connecting to the Socket IO object in Node.js using Express?

Encountering a strange issue on the remote server side where everything works fine locally with a self-signed cert over https. However, when moving the code to the server, it works locally but not remotely. A node app is created and hosted on the server u ...

Revamp the Twitter button parameters or alter its settings

I'm working on a web page that includes a Twitter button. Before the button, there is an input field and a form where users can easily add relevant hashtags for the page. The goal is to take the text from the input field and populate it in the Twitter ...

Issue with the statement not being recognized for counting the space bar

I created a counter but I'm having trouble incorporating if statements For example: if (hits == 1) {alert("hello world1")} if (hits == 2) {alert("hello world2")} if (hits == 3) {alert("hello world3")} if (hits == 4) {alert("hello world4")} This is t ...

Trouble with setting HTML table width

<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> </head> <body> <table border="1" width="100%"> <tr> <td>bbbbbbbbbbbbbbbbbbbbbbbbbbb ...

What is the root cause behind the recurring appearance of this line in Angular/D3.js?

I recently came across an excellent tutorial on integrating the D3.js library with AngularJS by following this link: . The guide provided has been extremely helpful in getting me started (big thanks to Brian!) However, I'm eager to delve deeper into ...

What methods can I use to minimize the duration of invoking the location.reload() function?

When I'm using window.location.reload() in my onClick() function, it's taking too long to reload. I tried modifying the reload call to window.location.reload(true) to prevent caching, but it's still slow. The issue seems to be with location. ...

ControlOrbiter - limit panning motion

Is there a way to restrict the camera's panning movement within a scene? I've experimented with adjusting the pan method in orbitControls, but I'm not completely satisfied with the outcome. I am hoping for a more convenient and proper solut ...

Tips for saving an array from the server into a script variable

I'm currently working with the express js framework along with Handlebarsjs as the templating engine. My aim is to pass an array from the router to the view, and then store this array within a script tag. //users is an array res.render('chatRoom ...

AngularJS inputs using ng-model should be blank when in the pristine state

Check out this input element within an HTML form: <input ng-model="amount" /> Currently, the input displays as $scope.amount = 0 in the controller. I want to start with a blank input field instead. This way, users can easily input data without havi ...

What is the best way to incorporate async/await in a useEffect hook in a React Native application?

Upon executing useEffect, my objective is to retrieve the token from AsyncStorage, fetch the data value using the axios.post('/auth/me') endpoint, and trigger the KAKAOLOG_IN_REQUEST action through dispatch. After verifying that the data value i ...

Programmatically extracting a list of utilized CSS images from IE WebBrowser (IHTMLDocument2)

Exploring the IHTMLStyleSheetsCollection, IHTMLStyleSheet, IHTMLStyleSheetRulesCollection etc. of IHTMLDocument2 to compile a list of all styles in the current document is quite simple. Does anyone have any suggestions on how to generate a list of only th ...

I am able to successfully receive accurate data in JSON format, however I am facing difficulties binding it to a jquery

I am struggling with integrating data fetched in JSON format using $.ajax into a table using jquery's datatable. Below is the JavaScript code I have been trying: $(document).ready(function () { $.ajax({ type: "POST", url: "Result.aspx/getUser ...

Displaying PHP output within a JavaScript expression

Let's dive into a scenario involving a basic HTML document and some JavaScript that's loaded within it: <!-- doc.html --> <!doctype html> <html lang="en"> <head> <script type="text/javascript" src=" ...

Troubleshooting problem with transmitting data using the b4j jQuery WebSocket library

I'm seeking guidance on the process of sending data through a custom library that connects to a Java server operating as a WebSocket server. The code I'm using for successful connection is: <script src="https://ajax.googleapis.com/ajax/libs/ ...

Displaying recursively retrieved data from an AJAX call on an HTML page using AngularJS

I am currently working on a recursive AJAX call where I receive server data in chunks. My goal is to display each chunk of data one below another on the front end. How can I achieve this without replacing previously received data with new data? I hope this ...

Ways to align a button in the center using Material-UI

I'm struggling to find a way to center buttons in Material-UI. Here is the code snippet I currently have: function BigCard(props) { const { classes } = props; return ( <div> <Card className={classes.card}> <C ...

swapping out an external CSS file in React for a new CSS file

My React app is quite large and includes four main CSS files (darkLTR, lightLTR, darkRTL, lightRTL), which may not be the most efficient setup. The templates were provided by my boss, and I was instructed to use them instead of Material UI, which I initial ...

The datepicker feature mysteriously vanishes when using Safari browser

When I utilize the jquery ui datepicker (range) and open my datepicker, if I scroll down the page, the calendar disappears. This issue seems to only occur on Safari browsers with mobile devices. Has anyone else experienced this problem? Would someone be ...