Using a JavaScript variable to control multiple CSS classes

Is there a way to assign multiple CSS classes to an HTML element, including one regular class and one or more JavaScript variables as classes?

I attempted to do this by adding it in as a typical script:

<div class="style-a <script type="text/javascript">style-b</script>">

However, I came across a suggestion recommending the following method:

<div onload="this.class=style-a;">

But I have a feeling that approach would only accommodate one class.

Any thoughts on how to achieve this? Thank you in advance.

Answer №1

Try utilizing setAttribute

const targetElement = document.getElementById('myTarget');
targetElement.setAttribute('class','newClass1 newClass2');

View the results here

Answer №2

Incorporating script elements into html attributes to insert data processed by dynamically assessed code is not a feasible practice.

Instead, a more suitable approach would be to utilize the following template:

<div id="#dyn-styles-1" class="style-a">
    <!-- contents of the div -->
</div>

<!-- ... -->

<script>
    //
    // Caution:
    //  - Execute _after_ the entire DOM has been constructed (use handlers for `load` or `DOMContentLoaded` events)
    //  - Proof of concept only: coding style not recommended for production use
    //
    var js_var_containing_class = "style-b";

    //...

    document.getElementById("dyn-styles-1").className += " " + js_var_containing_class;

</script>

You can avoid depending on IDs and instead reference existing css classes:

var el = document.getElementsByClassName("style-a");

for (var i=0; i< el.length; i++) {
    el[i].className += " " + js_var_containing_class;
}

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

Guide on using selenium webdriver (python) to choose, replicate, and insert all content within an element

Currently, I am faced with the task of transferring data from website A to website B as website A is soon going down. This includes not just text, but also images, hyperlinked text, and certain formatting requirements. Previously, the data transfer was don ...

Mastering the incorporation of Jquery $.Ajax within AngularJS

How can I implement normal jQuery Ajax in AngularJS? $.ajax({ type: "POST", url: window.apirooturl + "/logger", contentType: "application/json", data: angular.toJson({ url: $window.location.href, message: errorMessage, ty ...

Implementing jQuery function to hide or show content upon page load

Is there a way to have the content hidden when the page is first opened, but then revealed once a button is clicked? Any suggestions? <script> $(document).ready(function(){ $("#rooms").click(function(){ $("#rooms_box").show(); }); $("#faciliti ...

What is causing my array of objects to constantly accumulate undefined elements?

My quick sort function implementation for the object users_total_likes is behaving unexpectedly. When compiled and run in the terminal or browser, it adds undefined values causing a TypeError: if(users[i][key] >= users[hi][key] && users[j][key] ...

Utilizing KnockoutJS to Apply CSS Binding Based on Dropdown Selection

Check out the live example here: http://jsfiddle.net/0gmbbv5w/ In my application, I have an object retrieved from the database that I bind to a <select> var NoticeType = function (noticeType) { this.NoticeTypeId = ko.observable(noticeType.Notic ...

How can I get rid of the table borders and set colors for every other row in the

How can I remove the border lines from a table and assign colors to alternate rows in the table? Follow this link for the code: https://stackblitz.com/angular/kooxxyvddeqb?file=app%2Ftable-sticky-columns-example.css Thank you in advance ...

Using AJAX to send a request to a PHP file that populates a popover, but the functionality only works

I have created a basic search bar where with every .keyup() event, an asynchronous request is sent to a PHP file which then populates the data in a Bootstrap popover. The issue I am facing is that the popover displays the data only once. After entering th ...

Generating a default template for an Angular ag-Grid cell with a custom field name - how to do it?

I am currently working with ag-grid and have specific templates for many columns. However, some of the data I am inputting into the table are just plain text. I want to enhance the default case: <ng-template #defaultRecord let-record> ADDITIONAL E ...

"Customized Bootstrap button featuring a tooltip and modal, experiencing incorrect padding within the button group design

I encountered an issue with a button-group containing 2 buttons, each with a tooltip and a modal. Bootstrap recommends wrapping the buttons with spans to manage two "data-bs-toggle" attributes, which is what I initially did. While the functionality works ...

Execute a jQuery ajax request to a specific variable

For my Phonegap/Cordova project, I have implemented functions to handle all ajax calls in the following way: function requestData(action, id ) { var data = { user_id: localStorage.getItem('user_id') }; if( action == 'fee ...

AngularJS Validation does not verify the step limitation of an HTML number input field

Why isn't AngularJS validating the step="0.01" attribute in the second input? It seems to be working fine for the min and max attributes, but not for step. For instance: When entering 0.005, it still evaluates submitNewEntryForm.submitNewEntryAmount. ...

Determine the total character count in every paragraph

Looking for a way to tally up the number of characters in each paragraph on a webpage. Came across this handy snippet that counts words in paragraphs and it works like a charm. Wondering if it can be tweaked to also calculate the character count. There are ...

When viewed on mobile browsers, the side-by-side divs in a tabbed layout appear to be

Looking for some help with responsive design for the "PORTFOLIO ATTRIBUTES" tab on my website. On desktop, the content displays fine, but on mobile it overlaps and cuts off. Here's the link to the page in question: . Any suggestions on how to maintai ...

How come the values in my object remain inaccessible even after assigning values to it with navigator.geolocation.getCurrentPosition() and returning it?

After successfully assigning values to my pos object within the whereAmI function using navigator.geolocation.getCurrentPosition(), I can confirm that lat and lng are present inside the object. However, attempting to access these properties later on resu ...

The effectiveness of border-radius is limited to only one side of the div

After experimenting with applying the border-radius property to a div, I encountered an issue where the border radius only worked on one side when the radius value was too large. How can I resolve this problem while maintaining the border-radius value on a ...

the new adjustment has not taken effect on index.php

I have been working on my index.php file and have included various other files as well. Let me show you the structure: <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="style.css" /> <style type= ...

Sending an object to a Vue 2 component and confirming its validity

I am working with a Vue component that has numerous props. <Field v-for="field in fields" :key="field.name" :name="field.name" :type="field.type" :label="field.label" :values="field.values" :value ...

What is the best way to locate a specific button in jQuery?

How can I determine if the target of a click event is a button element in a document? $(document).click(function(e){ if(e.target.nodeName.toLowerCase() === 'button') { // Do something } Is the code above correct for this purpose ...

Using jQuery to eliminate selected item from a list

I have a basic list in html/jquery that allows users to add items. I am trying to create functionality where a specific item can be removed from the list when clicked on. However, the code for removing the item is not working as expected. Remove Item Code ...

Tips for implementing a confirmation dialogue box prior to submitting a form:

As a new developer, I am facing an issue that I believe you can help me with. I want to display a confirmation box before deleting. How can I achieve this in my Ajax code? HTML: <input type='button' class="btn btn-danger delete_button" id="de ...