Instead of outputting from array 2, a random output is chosen from array 1

How can I modify this code to output 2 distinct random array objects instead of just 1? I've tried so far but it only displays a single output. What could be the reason for this issue?

<!DOCTYPE html>
            <html>
                <head>

                </head>

                <body>
                    <script>


  
                        var myArray = [
                            "Apples",
                            "Bananas",
                            "Pears"
                        ];

    
                        var randomItem1 = myArray[Math.floor(Math.random()*myArray.length)];
                        var randomItem2 = myArray[Math.floor(Math.random()*myArray.length)];


                        document.getElementById("randomItem1").innerHTML=randomItem1;
                        document.getElementById("randomItem2").innerHTML=randomItem2;

  

                    </script>


                    <div id = "randomItem1"> </div>
                    <div id = "randomItem2"> </div>

                </body>

            </html>

Answer №1

Your solution is almost correct, but there are a few improvements you can make. Instead of overwriting your document body, consider creating two separate divs to display your random items.

Ensure that your JavaScript code is placed after the HTML content to avoid searching for elements before they are loaded on the page. Here's a revised version of your code:

<!DOCTYPE html>
<html>
<head>

</head>

<body>

<div id = "randomItem1"></div>
<div id = "randomItem2"></div>

<script>
var myArray = [
  "Apples",
  "Bananas",
  "Pears"
];

var randomItem1 = myArray[Math.floor(Math.random()*myArray.length)];
var randomItem2 = myArray[Math.floor(Math.random()*myArray.length)];

document.getElementById("randomItem1").innerHTML = randomItem1;
document.getElementById("randomItem2").innerHTML = randomItem2;
</script>

</body>
</html>

To test your code, you can use console.log(randomItem1) and console.log(randomItem2) in between the lines.

Answer №2

Two things are happening, one right and one wrong:

  1. Using

    document.body.innerHTML = randomItem1;
    will overwrite the existing elements

  2. When updating to something like

    document.getElementById("randomItem1").innerHTML = randomItem1;
    , the <script> block must be placed after the elements in order for them to be loaded and parsed in the DOM.

<!DOCTYPE html>
<html>
<head>

</head>

<body>

<div id = "randomItem1"> </div>
<div id = "randomItem2"> </div>

<script>
  var myArray = [
    "Apples",
    "Bananas",
    "Pears"
  ];

  var randomItem1 = myArray[Math.floor(Math.random()*myArray.length)];
  var randomItem2 = myArray[Math.floor(Math.random()*myArray.length)];

  document.getElementById("randomItem1").innerHTML = randomItem1;
  document.getElementById("randomItem2").innerHTML = randomItem2;
</script>

</body>

</html>


An alternative approach is to utilize an event listener that triggers when the DOM has finished loading.

<!DOCTYPE html>
<html>
<head>

</head>

<body>

<script>
  var myArray = [
    "Apples",
    "Bananas",
    "Pears"
  ];

  var randomItem1 = myArray[Math.floor(Math.random()*myArray.length)];
  var randomItem2 = myArray[Math.floor(Math.random()*myArray.length)];

  document.addEventListener("DOMContentLoaded", function(event) {

    document.getElementById("randomItem1").innerHTML = randomItem1;
    document.getElementById("randomItem2").innerHTML = randomItem2;

  });
</script>

<div id = "randomItem1"> </div>
<div id = "randomItem2"> </div>

</body>

</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implementing multiple perspectives on a single webpage by keeping track of the browsing history with AngularJS and leveraging the

Within my AngularJS application, I have an about page that contains various sub-sections, all within the same template. My goal is to have each section accessible through its own unique URL that will automatically scroll down to the corresponding section i ...

The element type provided is not valid: it should be a string (for built-in components) or a class/function. Utilizing SSR with Node.js, React, and React-

Playground: https://codesandbox.io/s/focused-dream-ko68k?file=/server/server.js Issue Error: Encountered an error stating that the element type is invalid. It was expecting a string or a class/function, but received undefined instead. This could be due ...

Permanently dismiss Bootstrap 4 alert using a cookie

Recently, I came across a bootstrap 4 alert that I found quite useful. Here is the code snippet for it: <div class="alert alert-warning alert-dismissible fade show" role="alert"> <button type="button" class="clo ...

Update the nested radio button to a new value

I have a series of radio button lists generated using ng-repeat. I've managed to capture the selected item successfully. Now, I am attempting to set the default value for the radio buttons. Could someone please provide assistance? Below is my code sni ...

Vue Router Guard Failing to Work Properly After Page Reload

I have implemented a router guard to protect certain pages in my app. The goal is for users to be prompted to log in when attempting to access these protected pages. Currently, the guard works as expected within the app itself. However, if a user refresh ...

If the option of "none" is chosen, I would like to deactivate all checkbox selections

Struggling with disabling all checkboxes in a PHP form when the NONE option is selected. <h5>HEALTH OF STUDENT</h5> <p>Any physical, emotional, or other difficulties to be aware of?</p> <table> <td>Hearing ...

Is there a way I can sort an array by checking if a key exists in an object?

I am currently working with code that filters data based on specific keys - in this case, "bounced" or "opened". Filtering for "bounced" items is working perfectly, but I am facing an issue with "opened" items. The key "opened" only exists if a message has ...

Node.js and MySQL: Troubles with closing connections - Dealing with asynchronous complexities

I am currently working on a Node program to populate my MySQL database with data from files stored on disk. While the method I'm using seems to be effective, I am facing challenges in ensuring that asynchronous functions complete before ending the con ...

Function for Duplicating jQuery Events

I'm currently facing an issue where every time the browser is resized, a function is triggered. This function can turn a side panel into an accordion if the screen width meets certain criteria, or it can just display as an open side panel on larger sc ...

Click on a React component to receive its property

Hey there! I'm currently in the process of developing an app that allows users to search for books and organize them onto specific shelves with just a click. Right now, users can type a query and see multiple results displayed on the screen. My goal i ...

Exploring Amcharts using detailed JSON data

[{"SUM_PTS":{"datatype":"INTEGER","length":"8","value":"29903727","obfuscated":"false"},"SUM_TOTAL":{"datatype":"INTEGER","length":"10","value":"1644704985","obfuscated":"false"},"MID":{"datatype":"ALPHANUMERIC","length":"27","value":"Vendor 1","obfuscated ...

jPlayer - Utilize the setMedia() function to define the media source URL

Having some trouble using jPlayer on Firefox 3.6 (Ubuntu) function loadmedia() { $('#jquery_jplayer_1').jPlayer('setMedia', { mp3: 'media/audio/04-Piste_4_1.mp3', }); } $(document).ready(function () { $('#jque ...

Animating Three.js OrbitControls to smoothly rotate and face the front of a target object

I am trying to smoothly move the OrbitControls(camera) in front of an object (face side) when a button is clicked using tween.js. However, I encountered an issue where after changing the controls.target and panning too far from the target object, I can on ...

internet explorer causing issues with .html() method

My webpage is encountering an issue with Internet Explorer when using AJAX to retrieve data and the .html() function to change the content of a div. While Firefox, Google Chrome, Safari, and Opera work fine, IE 7, 8, and 9 do not respond to the .html() fu ...

Ways to extract pertinent information from a PHP API

I've been attempting to add parameters to my query, but I keep getting inconsistent results. Despite trying different methods, I haven't been successful. Take a look at the code below. First, here is my code that functions properly without using ...

What is the process for retrieving data from mongoDB and displaying it by year in a single row?

I have received an array of data from MongoDB, which includes id, userName, and date. The date consists of years and months. My goal is to display this data categorized by years. How can I construct a query to the database that will show the data for all y ...

What is the best way to secure the installation of python packages for long-term use while executing my code within a python shell on NodeJS?

I have been encountering difficulties while attempting to install modules such as cv2 and numpy. Although I have come across a few solutions, each time the shell is used the installation process occurs again, resulting in increased response times. Below i ...

Transmitting data to a PHP script via AJAX and receiving a delayed response is not ideal for my needs

I am currently working on a contact page and have set it up to send a response if an invalid email is entered. However, the current code sends back an error message if a field is missing or left blank before clicking send. You can view the page at I still ...

What is the best way to integrate Google Maps into a Vue component?

I found a helpful reference on how to retrieve the formatted address from a dragged marker in Google Maps using JavaScript in this Stack Overflow thread. Now, I am looking to implement this functionality in a Vue component. I attempted to do it like this ...

This function named error is implemented in native code

My website is built in C# using asp.net. When the Onchange() event is triggered on the Dropdownlist, I call this jQuery function which displays an error: function error(){[native code]} <script type="text/javascript"> function GetDescription ...