简体   繁体   中英

How i can create multiple random paragraph elements with javascript?

I am trying to create multiple paragraphs with random text using the values in this array:

var values = ["Carl","Maria","Joseph","Tatiane","Dayanne"];

But honestly I do not know how to do that; this is my code...

var paragraph = document.createElement("p");
paragraph.innerText = "random string";
document.body.appendChild(paragraph);

I need to create 35 paragraphs ...

innerText is a quirky nonstandard property that IE introduced. It is highly recommended to instead use the standard, quicker, more reliable textContent instead - see http://perfectionkills.com/the-poor-misunderstood-innerText

You can get a random element from an array using arr[Math.floor(Math.random() * arr.length)] :

 const words = ["Carl","Maria","Joseph","Tatiane","Dayanne"]; Array.from({ length: 35 }) .forEach(() => { const randomText = words[Math.floor(Math.random() * words.length)]; document.body .appendChild(document.createElement("p")) .textContent = randomText; }); 

<script>
    var values = ["Carl", "Maria", "Joseph", "Tatiane", "Dayanne"];
    var total = 35;

    for (count = 1; count <= total; count++) {
        // Get random index within the array bounds
        var randomIndex = Math.floor(Math.random() * values.length);

        // Get value in the array that corresponds to the random index.
        var value = values[randomIndex];

        // Create the <p> tag.
        var p = document.createElement('p');
        p.innerText = value;
        document.body.appendChild(p);
    }
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM