Using JavaScript to append a class, rather than replacing it

I am looking for a way to add a class to an element without replacing the existing classes already assigned to it.

Below is the current javascript code that I have:

function black(body) {
var item = document.getElementById(body);
    if (item) {
        item.className=(item.className=='normal')?'black':'normal';
    }
}

This piece of javascript code replaces any existing classes with 'black'. If the class is already 'black', it is changed to 'normal'.

I would like to find a way to combine this script with the following script, which simply adds a class instead of replacing all existing classes:

var item = document.getElementById("body");
item.className = item.className + " additionalclass";

Answer ā„–1

Check out these basic plain javascript functions designed for altering class names in pure javascript. These functions are crafted to specifically match entire class names and eliminate any extra spaces before or after the classnames:

function removeClass(elem, cls) {
    var str = " " + elem.className + " ";
    elem.className = str.replace(" " + cls + " ", " ").replace(/^\s+|\s+$/g, "");
}

function addClass(elem, cls) {
    elem.className += (" " + cls);
}

function hasClass(elem, cls) {
    var str = " " + elem.className + " ";
    var testCls = " " + cls + " ";
    return(str.indexOf(testCls) != -1) ;
}

function toggleClass(elem, cls) {
    if (hasClass(elem, cls)) {
        removeClass(elem, cls);
    } else {
        addClass(elem, cls);
    }
}

function toggleBetweenClasses(elem, cls1, cls2) {
    if (hasClass(elem, cls1)) {
        removeClass(elem, cls1);
        addClass(elem, cls2);
    } else if (hasClass(elem, cls2)) {
        removeClass(elem, cls2);
        addClass(elem, cls1);
    }
}

If you desire to switch between the black and normal classes without impacting any other classes on the specified object, you can accomplish it like this:

function black(id) {
    var obj = document.getElementById(id);
    if (obj) {
        toggleBetweenClasses(obj, "black", "normal");
    }
}

Check out a working example here: http://jsfiddle.net/jfriend00/eR85c/

If you wish to add the "black" class only if "normal" is not already present, you can do so with this function:

function black(id) {
    var obj = document.getElementById(id);
    if (obj && !hasClass(obj, "normal")) {
        addClass(obj, "black");
    }
}

Answer ā„–2

If you don't anticipate needing to add, remove, or toggle classes frequently, a simpler approach like the code below may be more suitable than creating multiple functions as suggested in jfriend00's answer.

Here is an alternative method for those who prefer not to clutter their code with numerous functions that won't be used often:

function toggle(id) {
    var obj = document.getElementById(id), str, len;

    if (obj) {
        str = " " + obj.className + " ";
        len = str.length;

        str = str.replace(" normal ", " ");

        if (str.length != len) {
            str += " black";
        } else {
            str = str.replace(" black ", " ");

            if (str.length != len) {
                str += " normal";
            }
        }

        obj.className = str.replace(/^\s+|\s+$/g, "");
    }
}

This function stores the length, attempts to replace a class, checks if it was successfully removed by comparing old and new lengths, and then applies the necessary changes.

Note: This method will toggle classes smoothly under the condition that the two classes are not present simultaneously from the start.

DEMO

Answer ā„–3

It's uncertain if this solution aligns with your requirements as the solutions provided appear quite complex to me. Nevertheless, I found a way to add a new class without removing the existing one. Here's how I implemented it:

menu.children[i].getElementsByTagName('a')[0].**classList.add('resetAfter')**;

In this code snippet, I utilized the classList.add() method to append classes to an anchor tag.

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

Material UI Grid has a problem with inconsistent column width when using direction='column' and flexWrap='wrap' attribute combination

I'm a newcomer to React and Frontend development in general. Currently, I am working on setting up a MUI Grid that organizes items in columns which wrap around when necessary. So far, I've been able to accomplish this by adjusting the direction a ...

What is the best way to send variables from one page to another using jQuery or Javascript?

Is there a way to use POST with jQuery/Javascript to send data to another page and then redirect to that page? Instead of using GET... Using Javascript window.location = 'receivepage.php?variable='+testVariable; Once it's received by PHP ...

Can you explain the significance of this code snippet 'true <=> false'?

Today I came across this piece of code: true <=> false. I'm a bit confused by it and don't really understand how it works. If anyone could shed some light on this expression for me, I would greatly appreciate it. For reference, this code ...

What is the best way to achieve CSS rounded corners while keeping the border lines sharp?

Currently, I am utilizing the border-radius property to make the corners of a div rounded. In addition, there is a border line at the bottom of the div. Here is an example: <div style="border-radius: .5em; border-bottom: 1px solid black">Content< ...

Mastering CSS Sprites: A Guide to Aligning Sprite Buttons at the Bottom

In my web app, I have a bottom navigation bar with 9 buttons, each represented by a Sprite Image having 3 different states. The challenge I'm facing is aligning all the images at the bottom of the nav bar or div. The icons vary slightly in size, and ...

Creating a half-page Bootstrap Carousel: Steps and Tips

Is there a way to make this Bootstrap 3 carousel half-page? I'm struggling to figure out what adjustments need to be made in order to achieve that. It displays well in a small window, but once I expand it to full screen, the carousel takes over the en ...

"During page initialization, Angular.js and Node.js communicate with each other to trigger Node

When I try to invoke a node function upon loading a page using Angular, the function doesn't seem to execute. I have specified the ng-app and controller, and thought putting the API call in the controller constructor would work. Below is the code snip ...

Encountering Issues with NextJS Dynamic SSR: Mobile Devices stuck on loading screen

Issue: The dynamic import feature of Next JS is encountering loading issues specifically on mobile browsers such as Google Chrome and Safari on IOS. Strangely, the functionality works smoothly on desktop browsers like Google Chrome and Mozilla. The projec ...

The oddity of a lone quotation mark trying to break

var x = "Test \'" > undefined var y = "Test '" > undefined x === y > true x > "Test '" https://i.stack.imgur.com/ZrHo5.jpg Aha! Both of these strings are actually equal (as shown in the example code) - but why is that the ...

Troubleshooting: Issue with AJAX xmlhttp.send() functionality

I'm new to AJAX and have been stuck on the same issue for hours. Here is my script code: <script language='javascript'> function upvote(id ,username) { var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = fun ...

Accessing the scope value in Angular JS beyond the HTTP call

I am faced with a situation where I have multiple select boxes, each requiring data from different URLs to populate them. I am trying to load the response data into these boxes using the following code: function getFilterDataUrl(category_url) { var filt ...

Guide on parsing a JSON array passed from JavaScript using json_decode?

I am attempting to send JSON string encoded data to the PHP backend. In order to achieve this, I am utilizing a GET parameter with URL encoded JSON data in the form of an array similar to this: ["mystring1","mystring2"] However, when I try to decode it us ...

Prevent draggable canvas elements from overlapping using jQuery

I'm currently working on a project where I need to make three canvas elements draggable while preventing them from overlapping each other. After researching similar issues, I came across the "jquery-ui-draggable-collision" library. Here is the code I ...

Display content in .innerHTML continuously with Javascript and a while loop

I'm currently learning how to implement while loops in my code. I understand the concept quite well, but I'm facing some difficulty in using a while loop to write text repeatedly to an HTML element. var userText = prompt("Enter the text you wa ...

The container div contains a pop-up that expands the height of the container, rather than overlapping on top

I am currently developing a grid system similar to Excel, but I am encountering issues with displaying pop-ups properly as the lower part gets cut off by the container div. This problem is reminiscent of a situation discussed in a Stack Overflow post titl ...

Persistent white line in flexbox item that refuses to disappear

https://i.sstatic.net/BKHZV.png Iā€™m struggling to find a solution for the white line issue on the image. If anyone can explain why this is happening, I would greatly appreciate it. Despite my attempts, I have been unable to remove it even after inspecti ...

Using AngularJS and SpringMVC for uploading multiple files at once

Having recently delved into the world of angularJS, I've been attempting to upload a file using angular JS and Spring MVC. However, despite my efforts, I have not been able to find a solution and keep encountering exceptions in the JS Controller. Bel ...

What is the best way to hide the next/previous tabs once the jQuery dataTable has been set up using jSON data

Setting up a jQuery table using JSON data. Despite knowing that there will only be one row, the next/previous tabs are still displayed after the table. Is there a way to remove them? Here is the code for the table: table = $("#retrievedTable").dataTabl ...

Error Handling with Node.js Sequelize RangeError

Currently, I am in the process of setting up a table to store user sessions. Specifically, I plan to save the IP address as an integer and have been exploring various methods for achieving this. You can find more information on this topic here: IP-addresse ...

Why isn't the background-image : url() function cooperating in TypeScript?

I am facing an issue in my Rails project where I am trying to toggle the visibility of an image when a user clicks on it. Below is the code snippet I have implemented: $(document).ready(function() { if ($("#myvideo").prop('muted', true)){ ...