add a class to randomly selected tags in javascript

Viewed 17

I have stored 5 random custom tag elements named logocon from the DOM. I want to add a class to each of those randomly selected tags only. here is the code that gets 5 random tags. I tried .addClass() but it does not work.

  randomElements = jQuery("logocon").get().sort(function(){ 
        return Math.round(Math.random())-0.5
    }).slice(0,5)
1 Answers

randomElements is an array of DOM elements, not a jQuery collection. You can wrap it with $() to convert it to a jQuery collection so you can use .addClass().

$(randomElements).addClass('newclass');
Related