This is an example where I am going to show you how to write random elements to div having class names from array using JavaScript.

Let’s consider we have multiple div tags on a web page and these div tags are created dynamically based on certain condition but you are not sure how many div tags will be created on the page.

Therefore it would be wise to put class names for the div tags instead of id attributes for all of them. Because we cannot put multiple id attributes with the same value for each of the div tags.

Another option would be to give the unique id value to each div tag but later it will be difficult to figure out the id value for each of the div tag. So it would be better to have the class name for each div tag.

Having class name to each div tag would have a problem with the content because we may write the same content to all of the div tags.

Therefore we are defining an array with elements and randomly choose an element from the array to write to each of the div tags.

Let’s see how to do it in the following example.

Let’s say we have the following div tags in side the body of the HTML content. Even your content gets generated dynamically but eventually your content on the web page is in HTML format.

<div>
	<div class="content"></div>
	<div class="content"></div>
	<div class="content"></div>
</div>

Let’s say we have the following content in the array:

c1 = 'Hi';
c2 = 'Hello';
c3 = 'Hey';

const msg = [c1, c2, c3];

The above content will be chosen for each div tag randomly.

Now we will select the div tags in using the following piece of code:

var x = document.getElementsByClassName("content");

Next step is to write content to each of the div tags randomly from the array.

const len = x.length;

for(var i=0; i<len; i++) {
	x[i].innerHTML = msg[Math.floor(Math.random() * len)];
}

When you test the example code given above, you will see the following output on the browser. Each time you refresh the page, you will see different output at different div tags.

write random elements from array to div having class names using javascript

Source Code

Download

Thanks for reading.

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *