Is it possible to perform a forEach operation on two separate arrays simultaneously?

I have created two arrays and then utilized a function to assign values to certain variables based on the element clicked in the array. (Refer to the first code snippet) However, I am now looking to execute another function that makes use of these assigned variables. (Check out the second code snippet)

var wordEl;
var ansEl;
var wordId;
var ansId;

englishWords.forEach(function (el) {
      el.addEventListener("click", populateWord, false);
      function populateWord() {
        wordEl = el;
        wordId = el.getAttribute("id");
      }
    });

germanWords.forEach(function (el) {
      el.addEventListener("click", populateAns, false);
      function populateAns() {
        ansEl = el;
        ansId = el.getAttribute("data-id");
      }
    });

The following code snippet represents the function I wish to run, but I am unsure where or how to integrate it. I am consistently encountering an error "Uncaught TypeError: Cannot read properties of undefined (reading 'remove')", yet when I test it in the console, it functions properly.

    function checkAnswer() {
      if (wordId == ansId) {
        wordEl.remove();
        ansEl.remove();
      } else {
        alert("Incorrect! Please try again.");
      }
    }

Here is the HTML structure:

<table>
  <td><div class="englishbutton" id="word1">introspection</div></td>
  <td><div class="englishbutton" id="word2">antidote</div></td>
  <td><div class="englishbutton" id="word3">ambiguous</div></td>
  <td><div class="englishbutton" id="word4">braggart</div></td>
  <td><div class="englishbutton" id="word5">alleviate</div></td>
</table>

<table>
    <td><div class="germanbutton" id="ans1" data-id="word1">Selbstbeobachtung</div></td>
    <td><div class="germanbutton" id="ans2" data-id="word1">Gegenmittel</div></td>
    <td><div class="germanbutton" id="ans3" data-id="word1">zweideutig</div></td>
    <td><div class="germanbutton" id="ans4" data-id="word1">Angeber</div></td>
    <td><div class="germanbutton" id="ans5" data-id="word1">lindern</div></td>
 </table>

Answer №1

To implement a button that calls the function, follow these steps:

var wordEl;
var ansEl;
var wordId;
var ansId;

const englishWords = document.querySelectorAll('.englishbutton');
const germanWords = document.querySelectorAll('.germanbutton');

englishWords.forEach(function(el) {
  el.addEventListener("click", populateWord, false);

  function populateWord() {
    wordEl = el;
    wordId = el.getAttribute("id");
  }
});

germanWords.forEach(function(el) {
  el.addEventListener("click", populateAns, false);

  function populateAns() {
    ansEl = el;
    ansId = el.getAttribute("data-id");
  }
});

function checkAnswer() {
  if (!wordEl) {
    alert("Please select an English word");
    return;
  }
  if (!ansEl) {
    alert("Please select a German word");
    return;
  }
  if (wordId == ansId) {
    wordEl.remove();
    ansEl.remove();
  } else {
    alert("Incorrect! Please try again.");
  }
}
<table>
  <td>
    <div class="englishbutton" id="word1">introspection</div>
  </td>
  <td>
    <div class="englishbutton" id="word2">antidote</div>
  </td>
  <td>
    <div class="englishbutton" id="word3">ambiguous</div>
  </td>
  <td>
    <div class="englishbutton" id="word4">braggart</div>
  </td>
  <td>
    <div class="englishbutton" id="word5">alleviate</div>
  </td>
</table>

<table>
  <td>
    <div class="germanbutton" id="ans1" data-id="word1">Selbstbeobachtung</div>
  </td>
  <td>
    <div class="germanbutton" id="ans2" data-id="word2">Gegenmittel</div>
  </td>
  <td>
    <div class="germanbutton" id="ans3" data-id="word3">zweideutig</div>
  </td>
  <td>
    <div class="germanbutton" id="ans4" data-id="word4">Angeber</div>
  </td>
  <td>
    <div class="germanbutton" id="ans5" data-id="word5">lindern</div>
  </td>
</table>

<button onclick="checkAnswer()">
  Check
</button>

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

JavaScript (geolocation) error: Unhandled TypeError - Invocation not allowed

Encountering the Javascript error "Uncaught TypeError: Illegal invocation" while executing the code var nativeGeoloation = window.navigator.geolocation.getCurrentPosition; nativeGeoloation(function (){ alert("ok")}); Despite attempting to call the code w ...

Mock asynchronous calls in a React component using Jest

I am new to using jest/enzyme and I am facing a challenge in mocking a call to an asynchronous function that returns a Promise. This call is within a react component's componentDidMount method. The purpose of the test is to verify that componentDidMo ...

"In Vim, learning how to create block comments is an essential skill to

I am seeking a way to streamline the process of generating block comments for documentation in vim. For example: /** * comment */ Are there any available plugins that can assist with this task? ...

React isn't updating the on-change value despite changes being made

In my React application, there is a file called EditTodos.js that is responsible for updating the to-do list. When I click on the "Edit" button, it triggers a pop-up modal component. import React, { useState } from "react"; import { Button, Modal } from " ...

Is there a way to determine whether a mouse-down event took place on the scroll-bar or elsewhere within the element?

Looking for a solution with my HTML div acting as a canvas containing various objects. The issue lies in the fact that when attempting to draw a selection rectangle by dragging with the mouse, if scroll bars appear due to the large size of the canvas, scr ...

Choosing from a list in Angular

I'm trying to make a dropdown menu that shows options in the format "code-description", but only displays the "code" portion when an option is selected. For example, showing "A-Apple" in the dropdown, but displaying only "A" when chosen. I am able to ...

I am encountering an issue where the $scope.modal is returning as undefined when attempting to open an Ionic template modal. What

I am currently developing an Ionic application for the iPad. Within one of my templates, I have implemented a treeview with items. My goal is to open other templates modally when users click on these items. However, I encountered an error stating that $sco ...

Removing vacant rows from a table using Jquery in asp.net mvc

In my partial view, I am using BeginCollectionItem to manage the code. <tr> @using (Html.BeginCollectionItem("QuoteLines")) { <td> @Html.HiddenFor(m => m.QuoteID) @Html.HiddenFor(m => m.QuoteLineID) </td> ...

Ways to superimpose images

Everything seems to be functioning correctly in my code, but I would like the output images to overlap slightly. This could possibly be achieved using margins, padding, or some other script. Additionally, is there a way to incorporate z-index so that the ...

Tips for handling two JSON array objects with JavaScript

This particular function public function groups_priviledges($user_id = NULL){ $data['groups'] = $this->priviledges_model->admin_groups(); $data['member'] = $this->priviledges_model->empAdminGroup($user_id); echo ...

Creating crisp and clear text within a three.js texture

I am currently incorporating a 512x512 SVG onto a circular plane in my project using the following code snippet: const texture = new THREE.TextureLoader().load('img/plane.svg'); ​ const material = new THREE.MeshBasicMaterial({ ...

Using JavaScript functions within PHP is not supported

Currently, I am utilizing Laravel for my backend operations. Within my setup, there exists a JavaScript function called StartJob() that facilitates Google crawling. In the scenario where I input a keyword, which is then cross-referenced with the database, ...

What steps can I take to resolve this issue when encountering an error during npm install?

As a newcomer to programming, I am embarking on the creation of a Discord bot using node and discord.js. My current hurdle involves the installation of a library named canvas, which seems to be causing issues. After developing and testing my application o ...

Sending back JSON arrays containing Date data types for Google Charts

One of my challenges involves using a 'Timelines' chart from Google Charts, which requires a JavaScript Date type when populating data. Here is my initial code snippet: var container = document.getElementById('divChart1'); var chart = ...

Could one harness the power of SO's script for adding color to code within questions?

Similar Question: Syntax highlighting code with Javascript I've observed that Stack Overflow utilizes a script to apply color coding to any code shared in questions and answers, making it resemble how it would appear in an IDE. Is this script pub ...

Detect both single and double click events on a single Vue component with precision

I did some online research but couldn't find a clear answer. However, I came across this article -> Since I didn't quite understand the solution provided, I decided to come up with my own inspired by it. detectClick() { this.clickCount += ...

AngularJS object array function parameter is not defined

Recently, I've been honing my AngularJS1x skills by following tutorials on Lynda and Udemy. One tutorial involved creating a multiple choice quiz. To test my understanding, I decided to modify the code and transform it into a fill-in-the-blank quiz. ...

Enhanced Fancybox Version 2 adjusts iframe width to fit content

I have been attempting to adjust the width of the iframe in fancybox v2 to fit my content properly. However, every time I try, the content appears too large within the iframe and requires horizontal scrolling to view it all. My goal is to see the entire wi ...

Tips for safeguarding AJAX or javascript-based web applications

Utilizing AJAX, this function retrieves information about an image in the database with the ID of 219 when a button is clicked. Any visitor to this webpage has the ability to alter the JavaScript code by inspecting the source code. By modifying the code a ...

Is there a different method I can utilize to create a conditional statement for assigning a value in JavaScript?

I have this code snippet that seems a bit unclear to me: if (!app.config.admin.examStatusId) { app.config.admin.examStatusId = exam.examStatus.dataPlus[0].id; } Do you have any suggestions on how I could rewrite this more clearly without using an if s ...