Difficulty in displaying JavaScript function output as text

I'm currently developing a program that randomly selects and prints a function from an array list. I am facing difficulties in getting the result to print correctly. Below is the snippet of code:

const hiddenElements = document.querySelectorAll(
  ".hidden",
  ".demo",
  ".hold",
  ".button",
  "hold"
);
hiddenElements.forEach((el) => observer.observe(el));

var exerciseList = [
  "10 push ups",
  "5 pull ups",
  "15 box squats",
  "10 jump squats",
  "8 single leg squats",
  "20 mountain climbers",
  "1 minute plank",
  "20 resistance band pull-aparts",
  "30 second bar hang",
  "15 second hangboard",
  "5 diamond push ups",
  "5 military/wide push ups",
  "15 lunges",
  "1 minute skip rope",
  "30 second wall sit",
];

var workoutElement = document.getElementById("workouts");

button.addEventListener("click", function () {
  var randomIndex = Math.floor(Math.random() * Math.floor(exerciseList.length));
  workoutElement.innerText = exerciseList[randomIndex];
  console.log(workoutElement);
});

Answer №1

It appears that the challenge you encountered involved inserting text into a webpage. To overcome this issue, you can utilize document.createElement() and document.body.appendChild(). Here's an example:

var exercises = [
  "10 push ups",
  "5 pull ups",
  "15 box squats",
  "10 jump squats",
  "8 single leg squats",
  "20 mountain climbers",
  "1 minute plank",
  "20 resistance band pull-aparts",
  "30 second bar hang",
  "15 second hangboard",
  "5 diamond push ups",
  "5 military/wide push ups",
  "15 lunges",
  "1 minute skip rope",
  "30 second wall sit",
];

var exerciseBtn = document.getElementById("exercises");
exerciseBtn.addEventListener("click", function () {
  var exercise = exercises[Math.floor(Math.random() * exercises.length)];
  var el = document.createElement('p');
  el.textContent = exercise;
  document.body.appendChild(el);
});
<button id="exercises">Get an exercise</button>

In your initial code, there were some other issues which I have addressed in my improved version. One of the main problems was the presence of multiple variables named exercises. I kept the large array as exercises, changed the button to exerciseBtn, and renamed the randomly selected workout variable to exercise.

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

Bluebird refuses to execute the then() function, despite the code that was functional before

I am in the process of constructing a node framework for my upcoming projects, with a focus on easy management. The framework already includes a configuration module. Recently, I implemented an error handler and made updates to the Config module to incorp ...

What is the best way to contain my content within a bordered box?

As a beginner in HTML and CSS, I have successfully created a basic website with a simple menu at the top that includes links to different pages like "Home," "About," and "Contact." The website will mainly feature information and images, but I believe it wo ...

Exploring the dynamics of Kendo UI's MVVM approach using J

Is there a way to make an ajax call in Kendo without involving the grid? I am new to Kendo and struggling to populate a span element with data fetched from one of my controller methods. The data is present as I can see it in the alert message, but it' ...

Looking for a way to easily swipe through videos?

My mobile phone viewport displays a series of pictures and videos, with the swipeleft/right function enabled for browsing. However, I noticed that while the swipe feature works fine for images, it stops functioning when a video is displayed. Can anyone p ...

Turn off all VuetifyJS transitions

Is there a way to completely turn off all transitions, such as the slide-x-transition or dialog modal scale transition, in VuetifyJS? ...

Top recommendation for ensuring that a component is not being displayed

Imagine a scenario where a component returns null in the render method based on a specific prop. How can you effectively use expect to ensure that the component is not rendered? For example: import React from 'react'; import { render, fireEvent ...

Identify and alert when the download has finished

Imagine having a drive link to download a zip file. Upon clicking the link, the download begins in the browser. After the download finishes, I would like to send an email notification to the user. Is this achievable? I am using a .NET application (C#) wi ...

Unlocking the API endpoints within nested arrays in a React project

{ [ "quicktype_id": 1, "quicktype": "Laptops", "qucik_details": [ { "type_name": "car", "type_img": "car_img" }, { "type_name": "van", "type_img": ...

Shift a Div to the left prior to stretching it out

I am trying to achieve a smooth leftward movement and expansion animation for a div. Currently, I am experimenting with class switching on click events to transition between the desired states. However, I am facing difficulty in making the element first mo ...

Tips for inserting information into HTML components in JSP

Hey everyone, I'm diving into JSP for the first time and I'm trying to wrap my head around how to display data from an ArrayList in my HTML. Can someone help me out? I'm thinking of doing something like this: <article> <p>< ...

Determine if a link can be activated or disabled

Controlling the clickability of a link and displaying an error based on the result of an ajax call is my current objective. <a class="lnkCustomer" href="http://localhost/viewcustomer" target="_blank" data-customerno="2 ...

Issue with background image repeating incorrectly when resizing

I've recently added an image as the background for my website using the following style: #whole_wrapper{ background-image: url(../images/wrapper_bg.jpg); background-repeat: repeat-x; width: 100%; float: left; height: 116px; } ...

Having difficulty transforming a JSON string into a JSON object using Javascript

Currently, I am working on a hybrid mobile application using Angular. I have a string that is obtained from a $http.jsonp request and I am attempting to convert the response into JSON format. After checking the validity of the JSON at , it appears to be va ...

What advantages does event delegation in JavaScript offer compared to using jQuery's event handling?

Vanilla JavaScript: parentNode.addEventListener("click", function(event) { if (event.target === childNode) { code here } }); versus jQuery: $(parentNode).on("click", childNode, function() {}); ...

Guidelines for choosing input using jQuery

I am looking to retrieve the value of an input using jQuery. Specifically, I need to extract the value of a hidden input with name="picture" when the user clicks on the حذف این بخش button by triggering the function deleteDefaultSection( ...

Displaying different elements using an anchor <a> tag

Within this example, I've created two functional components that mimic separate pages with differently colored <div> boxes. const Home = () => <div style={{background:'red', height: 100, width: 100}}></div>; const ...

Ways to incorporate conditional logic with URL query parameters in Next.JS

I'm trying to implement conditional logic based on a URL query. In this scenario, I want to greet Kátia Fantes dynamically when she visits localhost:3000/katia-fantes. Any suggestions on how to achieve this? import { useRouter } from 'next/rou ...

Implementing Multiple Shared Footers in Rails 3

Looking for a solution to display unique footers in Rails? For instance, displaying one footer on the homepage and another footer on the rest of the site. Has anyone successfully implemented this before? I was considering using an if statement based on th ...

Interactive Autocomplete Component

I am encountering issues with passing dynamic data to my autocomplete angularjs directive, which is built using jQuery-UI autocomplete. Below is the current code I am working with: HTML: <div ng-app="peopleApp"> <div ng-controller="indexCont ...

Display content in two columns. If the width of the left column is too narrow, move the content in the right column

In my layout, there is a wrapper div with two child elements: left div and right div. The left div contains text which can be lengthy, while the right div holds an image loaded asynchronously without known width: <div id="wrapper"> <div id="l ...