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

Listen to music on an Android device without disturbing anyone using an iPhone

I have an application built in Vue3 that plays a sound when a QR code is scanned. This feature works perfectly on Android and the web, but not when using the browser on iOS. I am struggling to identify the issue. Can anyone provide some insight? <qrco ...

jqgrid's date restriction is set to November 30th, 1999 at midnight

I have a table displaying DATETIME values. However, after editing the datetime value, it always changes to "1999-11-30 00:00:00", both in jqgrid and the database, regardless of the date entered. [Tue Mar 12 11:39:28 2013] [error] [client 171.43.1.4] PHP N ...

Chrome not triggering the fullscreenchange event

I've been attempting to track when the browser goes into fullscreen mode. Everywhere I look, this blog is mentioned as the go-to resource on the fullscreen API. According to this SO answer, it should work. Fullscreen API: Which events are fired? B ...

Converting a Curl command to a JavaScript POST request: best practices

Is it possible to convert the given curl code into a JavaScript post request that will function effectively in all browsers? curl https://connect.stripe.com/oauth/token \ -d client_secret=sk_test_f7PKXx5NRBFG5r41nTrPT7qB \ -d code="{AUTHORIZATIO ...

Use AngularJS to extract information from Wikipedia and display it

Just starting out with angularjs and attempting to pull data from Wikipedia to display on the front end. I managed to fetch the data using the php code below: $url = 'http://en.wikipedia.org/w/api.php?action=query&prop=extracts|info&exintro&a ...

Is NextJS rendering solely on the server, or is it capable of rendering on both

Within my users.js JSX file, I have an exported component that looks like this: ... return <MainContainer keywords="users"> export default Users During the process of SSR/SSG, the browser displays the users HTML (comprising of <li> t ...

What is the best way to display a header element in front of an article element?

I'm struggling with making my header element sticky and appear in front of my article. Modifying the z-index hasn't given me the desired result so far. Is the z-index ineffective when dealing with floating elements? Or is there a workaround to m ...

Disallow users from closing the tab or browser window

Is it feasible to create a loop on window.onbeforeunload that opens the current page repeatedly upon tab exit? Take a look at the code below - it works, but browsers may block it as a popup. window.onbeforeunload = function(e) { window.open(do ...

Looping through a JSON array and encoding it using the `

I am looking to retrieve data from the database using AJAX and populate a 'select' tag with that data. Each name should be displayed in its own 'option'. Here is the code snippet: Index.php: <label>Select:</label> <sel ...

Retrieving attribute values when using the .on function in jQuery

I currently have 10 links with the following format: <a href="#" data-test="test" class="testclass"></a> as well as a function that looks like this: $(document).on("click", ".testclass", function () { alert($(this).attr('data-t ...

Focused Filtering in DataGrid Pagination

Seeking to adjust the font size of numerical values (10, 25, and 50 as shown in the screenshot below) within rows per page selection within a pagination section of a DataGrid component. After inspecting each number, it was revealed that .MuiMenuItem-root ...

Obtain URL parameters prior to rendering with Next.js on the server side

Looking to retrieve the parameters from a URL coming from the Spotify API, for example: http//link.com/?code=examplecode. Is there a way to extract the value of "code" prior to rendering so that I can redirect it and transfer the code value to another p ...

What is preventing me from utilizing require in vue-router's routes.js file?

Vue-router typically requires the standard setup as outlined below: In main.js, the routes.js file is required and it usually contains code similar to this: //routes.js import Register from './components/Register' import Login from './comp ...

Issues with visuals in jQuery.animate

I have nearly finished implementing a slide down drawer using jQuery. The functionality I am working on involves expanding the drawer downwards to reveal its content when the handle labeled "show" is clicked, and then sliding the drawer back up when the ha ...

Issues with user-generated input not properly functioning within a react form hook

After following the example provided here, I created a custom input component: Input.tsx import React from "react"; export default function Input({label, name, onChange, onBlur, ref}:any) { return ( <> <label htmlF ...

Encountering an issue when utilizing a personalized directive with AngularJS

I'm encountering an issue with the "auto-complete" directive that I'm using from jsfiddle. The error message I'm receiving is iElement.autocomplete is not a function. Can someone help me troubleshoot and fix this error? directive.js starte ...

Obtaining the final field with the $in operator in Mongoose

I need to retrieve all person records that fall within a time frame specified by start and end dates, and have a place ID of either 1 or 2. Below is the query I am using: Person.find({ time: { $gte: start, $lt: end ...

Utilizing jQuery.ajax to Send an Array of Objects to a PHP Function

In this scenario, an array of objects is represented as follows: rectangle[0].width = w; rectangle[0].height = h; rectangle[1].width = w; rectangle[2].height = h; rectangle[3].width = w; rectangle[3].height = h; ... We need to figure out how to send thi ...

Following the execution of an AJAX request, the jquery script fails to run

I've encountered an issue with my website that utilizes pagination, filtering with jQuery and AJAX. Everything was functioning smoothly until I decided to switch my links to JavaScript links. When on the homepage without any filtering or pagination a ...