The parent div in my code contains a child span element. I then created a new div and appended a child span to it. Surprisingly, when I attempted to add the span to its parent

ist

Answer №1

The issue arises from the fact that placedOnAnswer and placedOnQuestion are declared as global variables. This leads to persistence of their values between different function calls, causing unwanted behavior when clicking on answers and questions in succession.

To address this problem, it's recommended to make these variables local to the function so that they are reset with each call, ensuring no carryover of previous states.

var spn = document.querySelectorAll("span");
var question = document.querySelectorAll(".question");
var answer = document.querySelectorAll(".answer");

function onspanclick() {
  var placedOnAnswer;
  var placedOnQuestion;

  for (var i = 0; i < answer.length; i++) {
    if (answer[i].id == this.parentElement.id) {
      placedOnAnswer = true;
      break;
    }
  }
  for (var i = 0; i < question.length; i++) {
    if (question[i].id == this.parentElement.id) {
      placedOnQuestion = true;
      break;
    }
  }

  if (placedOnAnswer == true) {
    for (var i = 0; i < question.length; i++) {
      if (question[i].childElementCount == 0) {
        question[i].appendChild(document.getElementById(this.id));
        console.log("answer not working");
        break;
      }
    }
  }
  if (placedOnQuestion == true) {
    for (var i = 0; i < answer.length; i++) {
      if (answer[i].childElementCount == 0) {
        answer[i].appendChild(document.getElementById(this.id));
        break;
      }
    }
  }
}

for (var i = 0; i < spn.length; i++) {
  spn[i].addEventListener("click", onspanclick);
}
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
/* CSS styles removed for brevity */
<body>
  <div class="container">
    /* HTML elements omitted for conciseness */
  </div>
</body>

Answer №2

  1. My mistake in logic was that when I clicked on the question div, the span would shift to the answer and I set placedOnQuestion = true.
for (var i = 0; i < question.length; i++) {
    if (question[i].id == this.parentElement.id) {
      placedOnQuestion = true;
      break;
    }
  }
if (placedOnQuestion == true) {
    for (var i = 0; i < answer.length; i++) {
      if (answer[i].childElementCount == 0) {
        answer[i].appendChild(document.getElementById(this.id));
        break;
      }
    }
  }
  1. Subsequently, when I clicked on the span now located in the answer div, I set placedOnAnswer = true. At this point, both placedOnAnswer and placedOnQuestion are true.
for (var i = 0; i < answer.length; i++) {
    if (answer[i].id == this.parentElement.id) {
      placedOnAnswer = true;
      break;
    }
  }
  1. Upon clicking again on the span, it appends to the answer div. Following that, there is a condition where it checks for placedonQuestion being true and places the span back on the answer div. Both conditions are met, resulting in the element being placed where it was before.
if (placedOnAnswer == true) {
    for (var i = 0; i < question.length; i++) {
      if (question[i].childElementCount == 0) {
        question[i].appendChild(document.getElementById(this.id));
        console.log("answer not working");
        break;
      }
    }
  }
  if (placedOnQuestion == true) {
    for (var i = 0; i < answer.length; i++) {
      if (answer[i].childElementCount == 0) {
        answer[i].appendChild(document.getElementById(this.id));
        break;
      }
    }
  }
  1. To resolve this error, I adjusted the JavaScript code by setting placedonAnswer= true and placedonQuestion= false. Both variables should never be true at the same time. I appreciate the help from those on stack overflow who provided answers to my questions as I continue learning from them.
for (var i = 0; i < answer.length; i++) {
                if (answer[i].id == this.parentElement.id) {
                    placedOnAnswer = true;
                    placedOnQuestion = false;
                    break;
                }
            }
            

            for (var i = 0; i < question.length; i++) {
                if (question[i].id == this.parentElement.id) {
                    placedOnQuestion = true;
                    placedOnAnswer = false;
                    break;
                }
            }

I am grateful for the assistance from everyone on stack overflow who contributed to resolving my issue. Your answers have helped me learn and improve.

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

Align text vertically within labels and links styled with bootstrap

When using bootstrap button styled labels and links with a larger height than default, the text tends to be vertically aligned at the upper side of the button. However, when using an actual button element, the text is centered vertically. Is there a way t ...

Which data types in JavaScript have a built-in toString() method?

Positives: 'world'.toString() // "world" const example = {} example.toString() // "[object Object]" Negatives: true.toString() // throws TypeError false.toString() // throws TypeError Do you know of any other data types that wi ...

Exploring the Jquery functionality: $(document).ready(callback);

Hey there, I'm struggling to run a function both on window resize and document ready. The issue is that when the resize event is triggered by mobile scroll, it's essential to ensure the height hasn't changed. Oddly enough, the code works fin ...

How can I update an Angular Datatable to display new JSON data?

I have a Datatable controller set up as shown below: //Module / Módulo var angularDataTables = angular.module("angularDataTables", ['datatables', 'datatables.buttons' , 'datatables.bootstrap']); //Controller / Controlador ...

Looking for guidance and bug assistance in HTML and JS, possibly involving PHP and MySQL. Can anyone offer advice?

I'm attempting to create an auto-complete feature for a forum (similar to the tags below) that will function within LimeSurvey. I am fairly new to this, so please provide explanations as if you were explaining it to a 5-year-old :) My objectives are: ...

The JS copy function is successful when operating on a single element, but it encounters issues when attempting to run on multiple elements, only copying

My code includes a copy function that copies the data from a textarea to the clipboard when a button is clicked. The functionality works perfectly for the first textarea, but for subsequent textareas, the buttons do not perform the copy action. Check out ...

Is it necessary for every single product to have its very own webpage?

As a newcomer to the world of web development, I'm uncertain about the standard practices. Currently, I am working on creating a small e-commerce website with a wide range of products. Is it recommended to give each item its own dedicated page? Furthe ...

What is the best way to transfer a data string from my HTML document to my server (using either Node or Express) and trigger a specific function with that data?

Currently, my node.js server is operational and successfully creating an excel document by fetching data from an API using Axios. Now, I am looking to implement a feature where users can input a string on my HTML page, which will then be sent to the web se ...

Using Angular 4: Redirecting Menu to Component with Electron

I am currently working on my first project using Angular 4 and Electron to develop a desktop application. One of the challenges I'm facing is figuring out how to redirect to a specific component when a submenu item is clicked after overriding the ele ...

"Need help with displaying dates in a Material-UI table in ReactJS? Learn how to easily convert a date object to

When working with the DatePicker in material-ui, it generates date Objects. However, I want to display the selected value in a table. To achieve this, I need to convert the Object to a string since it is not possible to pass an Object directly to a table c ...

Issue encountered when attempting to update a specific element within an array using Mongoose

Looking to update a specific object within an array. { "_id": "543e2f8e769ac100008777d0", "createdDate": "2014-10-15 01:25 am", "cancle": false, "eventDateAndTime": "2014-02-12 12:55 am", "eventstatus": true, "userPhone": "44444444 ...

Confused about the concept of an SWR subscription

As I navigate through SWR's various features, there is one that has caught my attention: SWR-subscription. The concept of "subscribing to real-time data sources with SWR" is unfamiliar to me and I am seeking an explanation along with a straightforward ...

Can Javascript (PWA) be used to detect fake GPS or mock GPS in applications?

Looking for a solution to prevent users from using Fake Location tools in my PWA application that gathers absence location data. Is there a method or package in JavaScript to detect the presence of Fake GPS installed on the device? ...

What happens when tabs are dynamically added on keypress?

I am encountering issues with this code snippet. $('body').on("keypress", ".message", function(e) { if ( e.keyCode == 13 && $(".message").val().length > 0 ) { input = $(".message"); // Check for join com ...

Chrome browser experiencing a disappearing vertical scroll bar issue on a Bootstrap Tab

<div class="tabs-wrap left relative nomargin" id="tabs"> <ul class="nav ultab" id="fram"> <li class="active"><a href="#history" data-toggle="tab" id="history1" >History< ...

Unleashing the Potential: Integrating a Scanner Device with

Currently, I'm facing the challenge of integrating a Scanner device with my Angular application. On one of the pages dedicated to scanning, users are able to view an alert indicating the connection status of the Scanner as well as any scanned document ...

Fade out a dynamically loaded content block using jQuery

I am currently developing a small app and encountering issues with deleting (fading out) dynamically loaded div elements using jQuery. The problem occurs when adding a new content box. If the page is reloaded and the content box is rendered normally (from ...

Is there a way to use Protractor to test ASP.NET WebForms (not Angular)?

I am completely new to using protractor for testing .NET Applications. I am currently in the process of creating an automation testing script from scratch. The following is the HTML code: <div class = "top"> <span id = "welcome"> <em>Hi& ...

Access your account using Google authentication within an Angular framework

My latest project involves creating an API that allows users to log in with Google by using the endpoint http://localhost:3001/api/v1/user/google. Here's how it works: A user clicks on the link http://localhost:3001/api/v1/user/google The endpoint h ...

Insert a clickable element within an HTML document

I have an idea for a questionnaire that includes questions and an interactive element at the end. At the completion of the questionnaire, there will be a button labeled "display answers" which users can click to reveal the correct responses. For example, ...