1

I would like to create a button similar to these:

  1. the orange "Generate Random List" button from here
  2. The grey "Generate Another!" button from here

As of now, I've done the following:

=========================================================================

   <button id = "button" onclick = "random_element()">click 
   here</button>   
   <h1 style = "color:pink;"> Project Title</h1>
   <p id = "ZZZ" style = "font-size: 14px; color: 
   #a8bcff;"></p>
<script>  
   var zzz = document.getElementById('ZZZ'); 

   var arr = ["aaa", "bbb", "ccc", "ddd"];  
 // how do we substitute these strings with HTML lists in arr?
    function random_element() {  
    zzz.innerHTML = arr[Math.floor(Math.random() * arr.length)]; 
                                              } 
</script>
    <ol id="list">
      <li>video1 to be randomly chosen/displayed on button click   </li>
      <li>video2 to be randomly chosen/displayed on button click   </li>
      <li>video3 to be randomly chosen/displayed on button click   </li>
      <li>video4 to be randomly chosen/displayed on button click   </li>
     </ol>

=========================================================================

I understand how to generate random elements in the form of text. But I don't know how to make a JS array that contains all of the html lists of iframes.

What's the proper way to reference and USE html content between <li></li> tags inside a JavaScript array?

1 Answer 1

1

It's not entirely clear what you are wanting to accomplish so I am not worrying about your random generator here and just showing how to associate a group of <li> by their indexing to the same index in the array shown.

var arr = ["aaa", "bbb", "ccc", "ddd"];

const lis = document.querySelectorAll('#list li');

lis.forEach(function(el, i){
   const btn = document.createElement('button');
   btn.textContent = arr[i];
   btn.addEventListener('click', function(){
      // do something with the array value
      console.clear()
      console.log('Btn index:', i, ' array value:', arr[i])
   })
   el.appendChild(btn);
});
<ul id="list">
  <li>One  </li>
  <li>Two  </li>
  <li>Three  </li>
  <li>Three  </li>
</ul>

Sign up to request clarification or add additional context in comments.

2 Comments

Why did we have to add multiple buttons? The goal was to have one button that's able to get and display the contents of one random <li></li>
Suggest you use search engine and research each of the methods used. Giving a line by line explanation is tedious and the code used is very standard apporach to looping over a collection of elements and adding event listeners

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.