Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get a random character from a span

Hi i have created a span element with a text in a containing 0s and 1s. Is there a way which i can randomly select any character in that span element. I know how to do this by putting each character inside a separate span element but i’m creating this for a background and there will be over 2500 0s and 1s.

Html

<span class="text" id= "text">0001111011110110101100001</span> 

JavaScript

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var text = document.getElementById('text');
var x = Math.floor(Math.random() * text.length);

>Solution :

This function will return a random character from your span content

let content = document.querySelector('#text').textContent;

function getRandomChar(str){
  return str.charAt(Math.floor(Math.random() * str.length));
}

console.log(getRandomChar(content))
<!-- I added another content just for better demonstration -->
<span class="text" id="text">00ABCDEFGHIJK</span>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading