Search code examples
javascriptjqueryhtmlrandomgetelementsbytagname

How to select a random HTML element from the body?


All I want is a way to select a random HTML element from the body (preferably with JavaScript or jQuery). It could range from the body itself, to a divide, to a paragraph that is embedded deep within several divides. I want to select this random element, and then be able to change its CSS style. This is particularly just for a fun easter egg for my website, but if anyone knows how to do this, that would be great.


Solution

  • Code does the following:

     var selectors = $('*:visible');
     selectors.eq(Math.floor(Math.random() * selectors.length)).css("border", "1px solid red")
    
    1. Selects all visible elements
    2. Generates a random number less than selected elements
    3. Selects based on the random number
    4. Assigns a red border