I have a dynamic list of things. How to select only 3 items (that has 2 words or less) randomly, and convert it to clickable links. So everytimes the page is reloaded, random 3 links are created. Im expecting to use something like:
innerHTML = '<a href="mysite.com/folder/' + url + text.toLowerCase().replace(/\bamp\b|[^A-Z0-9]+/ig, "-") + '">' + text + '</a>'
From this:
list 1 list 2 222 list 3 list 4 list 5 555 list .. list 99 list 100
To this:
- list 1
- list 2 222 (*ignore 3 or more words)
- list 3 (*selected randomly and pointed to mysite.com/folder/list-3)
- list 4 (*selected randomly and pointed to mysite.com/folder/list-3)
- list 5 55 (*ignore 3 or more words)
- list ..
- list 99 (*selected randomly and pointed to mysite.com/folder/list-99)
- list 100
Once the page has loaded, loop three times, each time grabbing a random li
and refreshing that grab until it meets the criteria of having fewer than three words and not having been used yet. Each time you find an li
that is valid, change the innerHTML
.
window.addEventListener('load', (event) => {
for (var i = 0; i < 3; i++) {
var randomLI;
while (!randomLI || randomLI.getElementsByTagName("a").length > 0 || randomLI.innerHTML.trim().split(" ").length > 2) {
randomLI = rando(document.getElementsByTagName("li")).value;
}
randomLI.innerHTML = "<a href=\"mysite.com/folder/" + randomLI.innerHTML.toLowerCase().replace(/\bamp\b|[^A-Z0-9]+/ig, "-") + "\">" + randomLI.innerHTML + "</a>";
}
});
<script src="https://randojs.com/1.0.0.js"></script>
<ul>
<li>list 1</li>
<li>list 2 222</li>
<li>list 3</li>
<li>list 4</li>
<li>list 5 555</li>
<li>list ..</li>
<li>list 99</li>
<li>list 100</li>
</ul>
I used randojs.com to simplify the randomness and make it more readable. If you want to use this code, make sure this is in the head tag of your html document:
<script src="https://randojs.com/1.0.0.js"></script>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments