Guide to updating the class attribute of an HTML article element using JavaScript

I am working with 6 different styles in CSS and I am trying to apply them randomly using the following code:

<script>
    function getRandom(max) {
        return "style" + Math.floor(Math.random() * max);
    }
    document.getElementById('YYY').innerHTML = getRandom(6);
</script>

Additionally, I need to add YYY to the article class.

<article class="YYY">

Unfortunately, this code is not functioning as expected.

Answer №1

To begin, assign an ID to the section element

<section class="YYY" id="uniqueId">

Next, apply a class to the section using the following code snippet

var sectionElement = document.getElementById("uniqueId");
sectionElement.className = getRandomClass(6);

Answer №2

Thanks for checking this out!

//custom plugin for randomization
(function($) {
    $.rand = function(arg) {
        if ($.isArray(arg)) {
            return arg[$.rand(arg.length)];
        } else if (typeof arg === "number") {
            return Math.floor(Math.random() * arg);
        } else {
            return 4;  // decided by a fair algorithm
        }
    };
})(jQuery);

//list of different classes to use
var items = ["class-1", "class-2", "class-3", "class-4", "class-5"];

//runs when the page loads
$("#addRandom").removeClass().addClass(jQuery.rand(items));

//button to add random class
$("#randomize").click(function() {
      var item = jQuery.rand(items);
     $("#addRandom").removeClass().addClass(item);

});
#addRandom {

display:block;
width: 100px;
height: 100px;

margin: 10px
}

.class-1 {
  background-color: purple;
}

.class-2 {
  background-color: blue;
}

.class-3 {
  background-color: green;
}

.class-4 {
  background-color: yellow;
}

.class-5 {
  background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="addRandom" class="">

</div>

<button id="randomize">randomize</button>

Answer №3

If you are looking to apply a CSS class to your element, the solution is quite straightforward:

document.getElementById("your-element").classList.add("your-class");

To find out more about this method, check out classList.

Answer №4

Appreciate everyone's help! I've come up with a code that successfully meets the requirements:

<script>
const sections = document.querySelectorAll('section');
sections.forEach(section => {
    function getRandomClass(max) {
        return "theme-" + Math.floor(Math.random() * max);
    }
    section.classList.add(getRandomClass(6));
});</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

Having trouble signing out in Nextjs?

As a newcomer to Reactjs and Nextjs, I am currently working on developing an admin panel. To handle the login functionality, I have implemented the following code in my index.js/login page using session storage: const data = { name: email, password: pa ...

What is the purpose of using square brackets in the angular.module() function in AngularJS?

const myapp=angular.module('myApp',[]); As someone venturing into the realm of angularjs, I have a question. What is the significance of using [] in angular.module()? If anyone could shed some light on this, it would be greatly appreciated. ...

Tips for positioning buttons in a row below dynamic text using Bootstrap 3

Is there a way to align buttons under a variable piece of text in Bootstrap 3? Currently, when the code example is viewed in full screen, the three buttons do not align horizontally. Current Behavior: https://i.sstatic.net/lEQ7o.png My goal is to have t ...

What's the best way to retrieve the quantity of each item through v-for in Vue?

In my Vue code snippet below: var itembox = new Vue({ el: '#itembox', data: { items: { cookiesncreme: { name: "Cookies N Cream", description: "description" }, ch ...

Developing a hover-triggered tooltip feature in a React application

A tooltip has been created that appears when hovering over an element, displaying the full name of the product called productName. <div className="product-select-info" onMouseEnter={e => productNameHandleHover(e)} onMouseLeave={productNameHand ...

"Utilizing lightbox JS to produce a centralized overlay across the entire webpage

Currently in the process of redesigning a gallery for a client at www.stagecraft.co.uk/gallery.html I am encountering some challenges with my overlay. I want it to be centered and on top of any divs that are currently in view, as new images from the clie ...

Organize elements with jQuery, remove, detach, clone, and append without worrying about memory leaks

I am facing a challenge with a parent div that contains approximately 300 child divs, each one containing an image and some text. I have an array with the necessary information to reorder these divs using references. However, whenever I loop through the a ...

The dual-file upload feature of the jQuery ajaxForm plugin

After extensive searching online, I have yet to find an answer to my problem. The issue at hand is that when using the ajaxForm malsup plugin, it submits my files twice. HTML: <form id="gallery" enctype="multipart/form-data" action="/upload-gallery.p ...

A guide on retrieving the upload status of a file using an AJAX post request

Is there a way to retrieve the status of uploaded files when the user cancels the process while uploading multiple files using an ajax call? This is how I am currently making the ajax request to upload files: var request = $.ajax({ url: 'file ...

Error: PHP is showing an undefined index error when trying to decode JSON, even though the value

I am feeling quite puzzled. I transferred a key value pair object from jQuery to PHP and successfully alerted it back out. However, when I visit the PHP page, it indicates that the data is either null or an undefined index. Here is my jQuery code: $(&ap ...

Having trouble with a beginner problem that's hindering the functionality of my code

I have been struggling with a particular piece of code and it is driving me crazy as I am unable to locate the source of my error: $.post($form.attr('action'), $form.serialize(), function (result) { console.log(result); if (result.succes ...

Is it possible for the JavaScript code to cease execution once the tab is closed?

I am working on a JavaScript code snippet that is designed to execute once a component finishes loading: function HelloThere() { React.useEffect(() => { setTimeout(() => { // code to make a server call to write data to DB ...

The wonders of JSON.stringify() and the dynamic world of JavaScript Objects

Maybe I overlooked something in my JavaScript knowledge and I'm just realizing it now. I was experimenting with this code snippet in the Chrome console: a = []; a.name = "test"; JSON.stringify(a); // this returns [] a = new Object(); a.name = "test ...

What is the best way to add three dots at the end of text when it exceeds the available space?

What CSS property is utilized to display three dots at the end of text when it overflows? ...

An odd glitch occurring when transferring data from $_GET to $_SESSION

Currently, I am utilizing Opauth for user authentication on my website through Twitter and Facebook. Upon their departure from the site, I store a redirect URL in the session to ensure that they are redirected back to the exact page they were viewing prev ...

I am experiencing an issue with the button that is supposed to link to a section within the same page while it is located within the jumbotron. Interestingly, the button

I'm facing an issue with a button placed inside my jumbotron. The button is supposed to link to a specific section within the page, but it's unresponsive. Even hovering over it shows no interaction. Strangely, if I move the button outside of the ...

CSS tabs are not functioning properly as hyperlinks

Having some trouble with this website: The tabs on the site are not functioning when clicked. I've implemented a hover effect using CSS, but I'm unable to get the tabs to work properly. Please advise. Thank you. ...

Receive the button click event outside of the canvas

Is there a way to have separate click events for the button and the ListItem? My focus is on the button click event only, without triggering the ListItem event. Live DEMO import React from "react"; import ReactDOM from "react-dom"; import ListItem from ...

The function 'compilation.emitAsset' is not recognized by the sitemap-webpack-plugin

I'm currently working on setting up a sitemap for my live environment and I've encountered an issue while trying to utilize the sitemap-webpack-plugin. The error message I received is as follows: ERROR in TypeError: compilation.emitAsset is not a ...

Tips on implementing .on() with querySelector in jquery?

Can you help me convert the jQuery code below into a querySelector method? <script type="text/javascript"> jQuery(function($){ $('#woocommerce-product-data').on('woocommerce_variations_loaded', function() { $ ...