Is there a way to dynamically update the text in an HTML element with a randomly generated value using JavaScript?

Currently, I am working on a coding project where I am attempting to create a flip box that reveals the name of a superhero from an array when clicked by a user. The code pen link provided showcases my progress so far: https://codepen.io/zakero/pen/YmGmwK.

The code functions as expected with the use of alert() in the code pen example. It randomizes and displays a superhero name each time a square is clicked. However, my goal is to have the result displayed after the square is clicked and flipped. Instead of showing "Back", I want it to reveal one of the random superhero names. I've attempted to achieve this by using both .textContent and .innerHTML methods but have been unsuccessful. Here is the snippet of code I've tried:

Javascript:

function setupSquares() {
    for(var i = 0; i < frontSquare.length; i++) {
        frontSquare[i].addEventListener("click", function() {
            var randomNumber = frontSquare[i] = generateRandomNumbers(numbers);
            for(var j = 0; j < superhero.length; j++) {
                var index = superhero.indexOf(superhero[j]);
                if(randomNumber === index){
                    backSquare.textContent = superhero[j];
                }
            }

        });
    }
}
... (remaining content unchanged)

Answer №1

If you want to access the .back of the .front element that was clicked, you can achieve this using the code snippet below:

this.parentNode.querySelector('.back').innerText = superhero[j];

In your scenario, there are some key aspects missing. Firstly, note that backSquare is an array, so you must specify which element within it you wish to update. Instead of using

backSquare.textContent = superhero[j];
, opt for
backSquare[i].innerText = superhero[j]
to target the same i-th element in backSquare as in frontSquare. However, be cautious because this approach might not work due to the use of var i = ... in the loop variable - var does not create a closure over the loop. To rectify this, consider switching from var to let.

For further information, refer to: Closures versus ES6 Let

Alternatively, you can utilize the keyword this which points to the current clicked element. This means that this will represent the element being clicked when used in conjunction with your addEventListener function.

To learn more about this: https://codeburst.io/all-about-this-and-new-keywords-in-javascript-38039f71780c

See a live demonstration here: https://codepen.io/anon/pen/JgbPEK

Answer №2

Another method to achieve the same result is by using this code snippet:

this.closest('.card').querySelector('.back').textContent = superhero[j]

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

How do I input text into a Google Doc using an XPATH or element that is difficult to manipulate?

I'm currently working on a Python code that is designed to automatically open a Google Doc and input a specific set of combinations for a predetermined length. While I've successfully created the code to navigate to my Google Docs and open a new ...

Guidance on exporting an Excel file from an HTML table, excluding the final row, using JavaScript

I'm able to export an Excel file from an HTML table, but I'm facing an issue where the last row (tr) meant for pagination on the screen is also being included in the exported result. How can I exclude this row from showing up in the Excel file? ...

Every time I attempt to insert a button from Semantic UI into my code, I consistently encounter an error message that reads: "Error: Unable to locate node on an unmounted

Struggling with a side project utilizing a MERNG stack. Can't seem to successfully add a button from semantic UI react documents into my code, sourced from here. Despite multiple attempts, encountering an error without clarity on the root cause. GitHu ...

Exploring Jasmine's Powerful Spying and Mocking Capabilities in JavaScript Prototypes

Hey everyone, I need some help with a JavaScript issue. So, I have a file named FileA.js which contains a prototype called FileAObject.prototype along with a function named funcAlpha(). Here's a snippet of what it looks like: File = FileA function s ...

Is it possible to utilize the userId instead of the jwt token in this scenario?

Is it a good practice to hash the userId and store it in local storage, then send unhashed user id in authorization header on every route for server-side validation? Will this approach ensure security? ...

Obtain the dynamic identifier of an element within every block using jQuery in a rails application

Let me illustrate my issue with a simple example. I am currently developing a recipe application. Within the show partial that loads via AJAX, I have the following setup: _show.html.erb <% @recipe.ingredients.each do |ingredient| %> <div class ...

How is it possible that I am still receiving spam emails even though I have already implemented reCaptcha

I recently integrated Google reCAPTCHA v3 into my HTML form to combat spam emails, but I'm still receiving unwanted messages. What steps can I take to further prevent spam without relying on PHP code and using only JavaScript scripts? Currently, my c ...

Regular expression designed to validate a 19 digit MasterCard number

I need assistance with adjusting the regex pattern for Mastercard to support both 19 digit and 16 digit cards. Can someone please provide guidance on how to modify it? masterCardPattern: /^(?:5[1-5][0-9]{2}|222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0- ...

Implementing the IF statement in jQuery

I've been trying to implement an overflow check when hovering over a div. The issue arises because I'm using jQuery for the hover function and then simple JavaScript for the overflow check in the next step. It seems that directly using an if-then ...

Identifying text within clicked divs using identical ids

$(document).ready(function(){ $('#peoplelayer').click(function(){ $(this).fadeOut(500); var str = $(this).text(); alert(str); }); }); This is code where I use the same id "#peoplelayer" for all the divs. When on ...

What is the best method for incorporating jQuery code into a separate file within a WordPress theme?

I'm fairly new to working with Javascript/jQuery, so please be patient with me. Currently, I'm in the process of creating a custom WordPress theme where I've been using jQuery to modify the main navigation menu generated in my header file ( ...

Adding custom script tags to a React application

I'm interested in integrating a StreamingVideoProvider video player into my React application but facing some challenges: I do not have direct access to the video URL I want to utilize their JS video player for its advanced features like password pro ...

What could be causing me difficulty in integrating NProgress into my Next.js application?

Despite following all the necessary steps for implementing the nprogress package, I am facing an issue where the loading bar shows up when routes are changed but nprogress fails to function properly. I have attempted alternative ways such as linking the st ...

The data is not retrieved in the response

When creating an order, I am encountering an issue where the code is not waiting for the meal data retrieval despite using async and await. This results in my response containing empty data. Although I prefer to use async and await over promises for consi ...

JavaScript's data.map function cannot be found

I've been developing a full stack application using Vue.Js, NodeJS, ExpressJS, and MongoDB. In my frontend code, I have a PostService.js class that manages HTTP requests to the API. However, I encountered an issue while trying to map the response data ...

The HTML to PDF file converter API performs well in a local environment but encounters issues when deployed on node.Js, Express.Js, html-pdf, and Azure Web Services platform

I've developed an API that converts HTML to PDF, and it works flawlessly in my local environment but encounters issues when deployed on Azure app web services. During the process of generating the PDF, the request gets stuck and eventually times out, ...

Completing the final touches on my jQuery typing enhancement feature

Currently, I have a code snippet that creates <li> elements with specific dimensions and background images when a user presses a key. The corresponding CSS class is applied to the generated <li>, displaying a specific character on the screen. H ...

What could be causing the issue where only the latest data is being shown

When I use ajax to retrieve data from my database, the console.log displays all the results correctly, but in my HTML, only the last result is shown. What could be causing this issue? Any help would be appreciated! Thanks! Please keep your response simple ...

Tips for displaying span value within asp.net web pages

I have an HTML code snippet that looks like this: <tr> <td> <span>Full Name:&nbsp;</span> </td> <td> <span id="FullName_PDLabel"><b>--</b></span> </td> & ...

Calculating the number of checked checkboxes using PHP and HTML

Greetings! I am just starting to learn php and I have a question about how to count the number of 'checkbox' items that are checked when I click on a submit button. Here is an example: <input type = "checkbox" value = "box" name = "checkbox1 ...