How to append a CSS class with JavaScript without removing existing classes

Utilizing a ddsmoothmenu involves dynamically adding a class name to the parent menu container through the plugin. Once applied, all CSS rules will also affect the menu. Below is an example of how the classname is passed:

<div id="myMenu">
  <ul>
     <li>.....</li>
  </ul>
</div>

The following code snippet demonstrates how the classname is dynamically added to the menu container by the plugin:

ddsmoothmenu.init({
    mainmenuid: 'myMenu',
    orientation: 'h',
    classname: 'ddsmoothmenu',
    contentsource: 'markup'
});

However, I encountered a challenge when trying to add a 'noindex' class to the menu container. The plugin replaced my class with whatever was provided in the 'classname' parameter above.

Specifically, this line within the plugin causes the issue:

$mainmenu.parent().get(0).className = setting.classname || "ddsmoothmenu"

In this context, $mainmenu refers to the unordered list element.

I considered using the simple += operator to concatenate classnames, but I'm unsure if that would work due to the ternary if..else setup in the code.

Is it possible to modify the line as follows:

$mainmenu.parent().get(0).className += setting.classname || "ddsmoothmenu"
?

I aim to retain the hardcoded class in the markup while allowing the plugin-generated class to be appended to it.

Answer №1

To apply multiple classes to an element in plain JavaScript, simply take the existing class name, include a space, and then append the additional class name. While using a library may be convenient, achieving this with native JavaScript is straightforward:

function addClass(newClass, elementId) {
    var targetElement = document.getElementById(elementId); // The method of getting reference to the element might differ
    var currentClasses = targetElement.className;
    targetElement.className = currentClasses + " " + newClass;
}

The way you target elements in the DOM may vary, but ensuring there is a space between each class name added should work seamlessly.

Answer №2

According to the jquery api documentation, the addclass function adds specific class(es) to each matched element in a set.

The version 1.0 of addClass( className ) expects a string input of one or more space-separated classes to be added to the existing class attribute of each element.

In version 1.4, addClass( function ) requires a function as input with arguments (Integer index, String currentClassName) that returns one or more space-separated class names to be added on top of the existing ones. The "this" keyword in the function refers to the current element in the set.

An example usage of jquery's addclass function can be seen here:

$( "p" ).last().addClass( "selected" );

It essentially adds the specified class to the selected element without removing any other classes present.

You can find more information about this function in the official jquery api documentation.

Answer №3

One of my go-to tools is classie. It offers a reliable solution for adding or removing classes in the DOM. What's great about it is that it includes a fallback for browsers that lack the classList function, such as IE8.

If you're just interested in the code snippet:

addClass = function( elem, c ) {
    elem.classList.add( c );
};

and

addClass = function( elem, c ) {
    elem.className = elem.className + ' ' + c;
};

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

How do we insert an element into an array with a fixed memory size?

Recently, I reached the Algorithm section of JavaScript and learned that an array cannot grow. However, I am confused about how we can push items into an array. Is the "array" copied and new memory added for additional items? ...

Tips on using CSS3 without relying on images

Can the following be designed using only CSS3 without the use of images? ...

What is preventing the Image Handler from being triggered by an AJAX client?

Below is the code snippet provided: Public Class Default4 Inherits System.Web.UI.Page Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Dim image1 As Image = Default4.GetSQLTable OtherBit ...

Stop the repetition of the HTML Script element running more than once

Currently, I am using Ionic 2 for the development of my app. Inside the index.html file, there are various scripts that execute when the application starts. My goal is to rerun app.bundle.js midway through a user's interaction with the app. Here is ...

Manipulating values within a multidimensional array using JavaScript

I am attempting to populate a multidimensional array with data from a JSON file. The issue I am facing is that I am unable to update the content in the array: if(j>i && hoursYy == hoursY && secondsX == secondsXx){ wocheArray[i].count = wocheArray[i] ...

What are the steps to downloading a server-generated image with user data from the client using Express?

I am facing a challenge with downloading a server-generated image immediately after it is created. My current approach involves using fetch to send user input data (bypassing HTML forms). Although the image is successfully generated on the server, I am str ...

Customize request / retrieve document cookies

I have successfully implemented a cookie in my express/node.js application. var express = require('express'); var cookieParser = require('cookie-parser') var app = express(); app.use(cookieParser()) app.use(function (req, res, next) ...

What is the method to ensure an element is displayed in Selenium WebDriver?

Looking for assistance on how to choose options from a dropdown when the element is not visible and has a boolean attribute? Here's the HTML code snippet: <select id="visualizationId" style="width: 120px; display: none;" name="visualization"> & ...

Develop a tree structure that showcases various directory paths

I have a multidimensional array containing various folder paths. My goal is to create a single tree structure from this array, similar to what you see when using the "tree" command in the terminal. Please excuse any mistakes in my English and forgive my li ...

`The search bar and search button`

On mobile, I have a search field and a button working fine. However, when typing in something and hitting "search" on the phone's keyboard, it leads to a 404 error. But clicking the "search" button works as expected. I would like to be able to hit "se ...

Creating multiple child processes simultaneously can be achieved by spawning five child processes in parallel

My goal is to simultaneously run five spawn commands. I am passing five hls stream urls to the loop, and these streamlink commands are meant to record the video for 5 seconds before terminating those processes. I have attempted various async methods but a ...

Setting up your NODEJS Express Server to handle POST requests: A Step-by-Step Guide

I am currently developing a quiz app that utilizes the Gemini API to generate questions. The frontend of the app is built using HTML, CSS, and Vanilla JavaScript, while the backend is powered by Node.JS with Express. Every time I make a fetch request usin ...

How can I display a spinner/loader gif when the page loads using Vue?

When it comes to loading components on a webpage, jquery has the options of $( document ).ready() and onload. But in Vue, how can we achieve the same effect? For example, when a user clicks our page, how can we display a spinner until all contents are load ...

Transform an object into an array using JavaScript with the help of Lodash, Azure Functions, and Azure Logic Apps

To achieve the desired result of extracting JSON from a proprietary content management system, transforming it into a CSV, and depositing that CSV in an Office 365 shared drive, a combination of Azure Function and Azure Logic App is utilized. The Node/Java ...

Avoid deleting a row in Sequelize if it is referenced in another association

Is there a method in Sequelize.js to trigger an exception when attempting to delete a row that is associated with another entity? For example, consider tables for Roles and Users. They have a many-to-many association, allowing any user to have multiple ro ...

Is it possible to render an SVG using PDFTron?

Before, I attempted to utilize an Annotation.StampAnnotation to make a personalized annotation while using an SVG as the foundation image. Unfortunately, I discovered that the StampAnnotation does not allow the user to alter or set the color. Thus, I have ...

Add an item to the second occurrence of a specific HTML class

I am facing a challenge where I need to add an element to another element, but the target element is only identified by a class that is used multiple times. Specifically, I need to append to the last or second occurrence of the element. You can see a visua ...

The debate between centralization and specification: the ultimate Javascript/jQuery best practice for web applications

Picture a scenario where a web application consists of numerous page groups (pg1, pg2, ...) and some of these page groups require specific JavaScript code that is only relevant to them, not the entire app. For instance, certain visual adjustments on window ...

Navigable Vuetify Tabs with routing capabilities

Within my Vue application, I have a page that contains various tabs. My goal is to display different tabs based on the routes being accessed. To achieve this functionality, I followed an answer provided in this link. Overall, it's working well! I ca ...

Is there a way to ensure the alignment of items remains consistent, especially for the rightmost column, by enclosing them within a div element?

I'm currently working with Vue.js and using a UI component framework designed for it. I'm facing an issue where aligning numbers like 500 or 5000, as well as icons, is proving to be difficult. The numbers in the rightmost column need to be aligne ...