Modify the class of an a-element using JavaScript

I'm not very experienced with Javascript, and I've encountered a frustrating issue.

My problem arises from having a list that contains other lists. I have a script that toggles the visibility of these lists on click. However, I also want to toggle/add a class to the link itself once it has been clicked.

This is an example of my list structure:

<ul>
    <li><a href="#" onclick="toggle('item1');">Click something</a>
    <ul id="item1" style="display: none;">
        <li>Something ...</li>
        <li>Something something</li>
    </ul></li>
    <li><a href="#" onclick="toggle('item2');">Click something else</a>
    <ul id="item2" style="display: none;">
        <li>Something more...</li>
        <li>Something something less?</li>
    </ul></li>
</ul>

Below is the script I am using:

<script type="text/javascript">
    function toggle(id) {
        var v = document.getElementById(id);

        if (v.style.display == '') {
            v.style.display = 'none';
            v.classList.remove("selected");
        } else {
            v.style.display = '';
            v.classList.add("selected");
        }
    }
</script>

The functionality for showing and hiding the list works correctly, but the class is not being added or removed as intended.

Here is the CSS code:

a:link {
    color: #000000;
    text-decoration: none;
}

a:hover, a.selected {
    color: #005b97;
    text-decoration: none;
    padding-left: 2px;
}

Thank you in advance for any help!

Warmest regards, Benjamin

Answer №1

JavaScript does not come with built-in functions for adding and removing classes

Give this a try

For adding a class

document.getElementById("MyElement").className += " NewClass";

To remove a class

document.getElementById("MyElement").className = 
   document.getElementById("MyElement").className.replace
      ( /(?:^|\s)NewClass(?!\S)/ , '' )

If you ever need to check if an element contains a specific class

function hasClass(element, className) {
return element.className.match(new RegExp('(\\s|^)'+className+'(\\s|$)'));
}

Answer №2

In vanilla JavaScript, the addClass / removeClass methods do not exist.

To achieve this functionality, you can utilize the HTML5 classList API or directly modify the element's v.className.

Answer №3

Effort was made to achieve the desired functionality with minimal code. Hopefully, it fulfills your requirements.

HTML:

<ul>
<li><a class="aSwitch" href="#" >Click something</a>
<ul id="item1" style="display:none">
    <li>Something ...</li>
    <li>Something something</li>
</ul></li>
<li><a class="aSwitch" href="#" >Click something else</a>
<ul id="item2" style="display:none">
    <li>Something more...</li>
    <li>Something something less?</li>
</ul></li>

CSS:

a:link {
color: #000000;
text-decoration: underline;
}

a.selected {
color: #005b97;
text-decoration: none;
padding-left: 2px;
}

jQuery

$('a.aSwitch').click(function() {
$(this).next().toggle();
$(this).toggleClass('selected');
});

Observe the functionality in action here: FIDDLE

Answer №4

Use the following code snippet to change the class of an element with a specific ID:
document.getElementById("idElement").setAttribute("class", "className");

Answer №5

To easily enhance the functionality of your code, consider integrating a jQuery addon.

<script src="../../Scripts/jquery-ui-1.8.11.min.js" type="text/javascript"></script>

Next, update your code to:

<script type="text/javascript">
function toggle(id) {
    var element = document.getElementById(id);
    $('#' + id).toggleClass("selected");
    if (element.style.display == '') {
        element.style.display = 'none';
    } else {
        element.style.display = '';
    }
}
</script>

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

Displaying truncated title text

Would it be feasible to display clipped text (overflow: hidden) in a way that is fully readable when hovered over? An attempt like this: div:hover { overflow: visible; background-color: yellow; } results in the text overlapping, making it impossible ...

Learn the process of showcasing database content on a webpage with an interactive feature that enables users to choose and access additional details

Apologies if this question has been asked before, I have searched for a solution but my web development knowledge is limited. To better understand my issue, you can visit the site at 000freewebhost by following this link: In summary, I am trying to select ...

There is a slight gap between the svg element and the path

Here is the size of my path tag (g tag is same size) https://i.sstatic.net/Huk8j.png This is the size of my SVG tag https://i.sstatic.net/VBXQi.png There is a gap between them. These are the inline attributes... <svg preserveAspectRatio="none" cla ...

PHP - Unable to verify session during script execution

I'm currently working on a PHP script with a lengthy execution time, and I am looking for a way to update the client on the progress of the script. Since the script is invoked via AJAX, output buffering is not a feasible option (and I prefer to keep ...

Most efficient method to upload numerous images without any lag

I have a website where images are loaded only when they are slightly below the viewport. This method allows the site to load initially without images and then determine which ones need to be loaded based on the user's viewpoint. When a user scrolls ...

How can I use JavaScript to show a div upon clicking an input element?

I am looking to make a block div visible when an input field is clicked. <input class="indifferent" type="radio" name="decision" value="indifferent"> Indifferent </br> <div class="input" style="display: none;"> Please assist with our com ...

The success function in ajax is failing to retrieve all the rows from the database

Recently, I encountered an issue with my ajax success function. It was working perfectly fine until it stopped returning a specific row from my database table, which is the gender_id. Below is the code snippet of my ajax function: function editProduct(pro ...

The error message "indexOf of undefined" appears when trying to read a property that does not exist within a new

Help Needed: The following error is happening: Cannot read property 'indexOf' of undefined at new HttpRequest (http.js:653) at HttpClient.request (http.js:1069) at HttpClient.get (http.js:1157) This occurs when I use the get() method from Ht ...

Error encountered when deploying ASP.NET application with Jquery Post

My Visual Studio 2015 website functions perfectly during debug mode on my personal computer. However, upon publishing the project to IIS, the second post encounters an error. ...

What advantages does incorporating SSR with dynamic imports bring?

How does a dynamic imported component with ssr: true differ from a normal component import? const DynamicButton = dynamic(() => import('./Button').then((mod) => mod.Button), { ssr: true, }); What are the advantages of one method over the ...

I have been utilizing ESBuild to compile JavaScript code for browser usage. However, I encountered an issue when trying to import CSS as I received an error message stating "Unexpected '.'". Can anyone provide guidance on how to resolve this issue?

I am currently developing a JavaScript notebook that operates within the browser environment. To compile my code, I have chosen to utilize ESBuild. My primary objective is to enable the handling of CSS imports such as <import 'bulma/css/bulma.css&a ...

Organize pairs of strings into a nested array within an array using Angular

Currently, I am working on a project in Angular. In this project, I have a string that contains special characters which I have successfully removed using regular expressions. Now, my goal is to arrange the first two strings within square brackets and the ...

How can I use jQuery to save different types of files like pictures and PDFs as 'mediumblob' in a MySQL database?

I am currently developing a tool for assessments and have encountered an issue with the logic: Whenever I click on 'Upload/View Files' within each question, a modal window pops up; Within the modal window, there is a section where you can s ...

What are the best practices for organizing jQuery AJAX requests to accommodate various input and output formats?

I have a single-page structured website and I am looking to implement Ajax functionality to update my data based on user interaction. My goal is to organize my ajax code in a way that is adaptable for different inputs and outputs. I want to be able to exec ...

MUI - Duplicating text within ListItemText

Is there a way to enable text copying from inside the component from material UI? If so, what changes can be made to achieve this? <ListItem key={staff._id} className={background_colour} onClick={par(set_viewing, component, sta ...

Ways to retrieve the baseURL of an axios instance

This question is being posted to provide an easy solution for fellow developers who may be looking for an answer. //Suppose you have an axios instance declared in a module called api.js like this: var axios = require('axios'); var axiosInstance ...

What is the best way to format a text component so that the initial word in each sentence is bolded?

Creating a text component where the first word of the sentence is bold can be a bit tricky. The current solution may result in a messy output like "Tips: favouritevacation" where there is no space after "Tips:". This approach is not very elegant. One pos ...

The ng-app feature is causing the script to run endlessly

Currently, I am troubleshooting an issue within my angular application that is built on the asp.net web application empty template. The problem arises when I utilize ng-app; if I leave it blank, the $routeProvider fails to initialize. However, if I specify ...

Trouble toggling Reactstrap navbar in my TypeScript project using NextJS

I recently integrated Reactstrap into my NextJS TypeScript project and encountered an issue with the Navbar component. Despite following the example from the Reactstrap documentation, the mobile toggle menu does not open when clicked. Additionally, none of ...

Error: Trying to play the Snake Game with the P5.js Library, but getting the message "(X)

During my journey of coding a snake game by following a tutorial, I encountered an issue that the instructor had not faced before. Strangely enough, I am unable to identify the root cause of this problem. To aid in troubleshooting, I meticulously commente ...