0

I have 6 styles in css and i want to use this code to apply them randomly:

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

And I need to add XXX to article class

<article class="XXX">

This code doesn't work :(

Lucio Paiva
  • 19,015
  • 11
  • 82
  • 104
  • you are trying to change innerHTML of element, not style. maybe this will helpful https://stackoverflow.com/questions/22577010/how-to-dynamically-change-css-style-attribute-of-div-tag – Abdul Aleem Jan 01 '19 at 13:09
  • `document.getElementById('XXX')` selects element by Id and you are not specifying any id. Use `
    ` or `document.getElementsByClassName('XXX')[0]`
    – Muhammad Usman Jan 01 '19 at 13:09
  • Could you add the original HTML and the end result that you want to achieve? It's a bit unclear to me what you actually want to do. – BenignBeppe Jan 01 '19 at 13:19

4 Answers4

0

First set a ID to the article tag

<article class="XXX" id="someId">

Then to set class to article use below code

var element = document.getElementById("someId");
element.className=getRandom(6);
Md. Nasir Uddin Bhuiyan
  • 1,598
  • 1
  • 14
  • 24
0

Hope this helps!

//randomize plugin
(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;  // chosen by fair dice roll
        }
    };
})(jQuery);

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

//executes on page load
$("#addRandom").removeClass().addClass(jQuery.rand(items));

//button to inject 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>
webkitfanz
  • 1,305
  • 1
  • 16
  • 29
0

If you just need to add a CSS class to your element, the answer is plain easy:

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

For more information, see classList.

Lucio Paiva
  • 19,015
  • 11
  • 82
  • 104
0

Thanks to all! Here is a code that works as needed:

<script>
const elements = document.querySelectorAll('article');
elements.forEach(element => {
        function getRandom(max) {
            return "style" + Math.floor(Math.random() * max);
        }
        element.classList.add(getRandom(6));
    });</script>