How can I make the onclick event work for all items instead of just the first json item that changes?

I am a beginner in JavaScript and I am not allowed to use jQuery or HTML in my assignment. I am trying to change the color of different items in my JSON when clicked, but it only works for the first item in the list. When I try to apply it to the second item by switching around IDs, it doesn't work.

for(var i = 0; i < content.length; i++){
  var contentText = content[i];

  var textCH1_2 = document.createElement("p");
  textCH1_2.id = "peterEntersRoom";
  if(content[i].id === "peterEntersRoom"){
    textCH1_2.innerText = contentText.text;
  }
  textContainer1.append(textCH1_2);
}

document.getElementById("peterEntersRoom").onclick = function() {
  document.getElementById("peterEntersRoom").style.color = "green";
}

The structure of the JSON is as follows:

{
    "chapter": 1,
    "id": "peterEntersRoom",
    "character": {
      "main_character": "Mrs. Darling",
      "supporting_character" : [
        "Wendy"
      ],
    },
    "dialogue" : false,
    "text": "Of course"
  },

Can someone please assist me?

Answer №1

Give this a try:

Take a look at the comments I've included below

    function bind(content){
            for(var i = 0; i < content.length; i++){
        var contentText = content[i];

        var textCH1_2 = document.createElement("p");
        textCH1_2.id = contentText.id;
        //if(content[i].id === "peterEntersRoom"){
            textCH1_2.innerText = contentText.text;
        //}
        textContainer1.append(textCH1_2);
        // Moved the eventhandler inside the for loop to associate with each text node
        textCH1_2.onclick = function() {
            this.style.color = "green";
        }
    }

   // document.getElementById("peterEntersRoom").onclick = function() {
   //   document.getElementById("peterEntersRoom").style.color = "green";
   // }
}

If your content.json file is structured like the example below:

[
{
"chapter": 1,
"id": "peterEntersRoom",
"character": {
  "main_character": "Mrs. Darling",
  "supporting_character" : [
    "Wendy"
  ]
},
"dialogue" : false,
"text": "Of course"
},
{
"chapter": 2,
"id": "HanaaLeavesRoom",
"character": {
  "main_character": "Mrs. Hope",
  "supporting_character" : [
    "Mark"
  ]
},
"dialogue" : false,
"text": "Good bye!"
}
]

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

What is the best way to store JSON data in Mongoose database?

I have some json data that I need to store in a mongoose database, but I'm struggling with how to structure my mongoose schema. data: { 'posts[0][commentId]': '0', 'posts[0][id]': '1', 'posts[0][post ...

Increase variable i by one after a given interval using the jQuery setTimeout function

I have been struggling with implementing a setTimeout function within a Wordpress loop to increment eq(i) for each individual post. Despite trying various approaches, nothing seems to be working as intended. Here is the snippet of my code: jQuery(document ...

Determine if a String Includes Characters Using If and Else Conditions

I am dealing with a string called uppercase, where if it contains letters nothing happens. However, if there are no letters in the string, then it evaluates uppercase. This is what I'm currently trying to accomplish using an if and else statement: ...

AJAX chat application's updating frequency

As I work on building a website that includes a feature for real-time chatting between users (similar to Facebook chat), I have implemented a system where messages are stored in a MySQL table called messages. This table contains the message ID, sender ID, ...

Using Axios to Integrate an API - Displaying a Username and Password Pop-up

I have been given a project that involves API integration. I have successfully retrieved data from the API, but there is a pop-up appearing asking for a username and password. Although I have these credentials, I would like to log in without that pop-up ap ...

Having trouble sending a function as a prop to a child component in React

Something odd is happening, I'm confident that the syntax is correct, but an error keeps popping up: Error: chooseMessage is not a function // MAIN COMPONENT import React, { useState } from 'react' export default function LayoutMain(prop ...

Pass an item along with its superclass using express

Is there a way to send an object from an express server and then check the instanceof of that object on the receiving end? I am working on integration tests for express and need to verify the instanceof of the response body. Unfortunately, it seems like t ...

Trouble with the back button functionality following logout

Despite hours of research and following various links, I am still experiencing a problem where my page continues to load after logging out and clicking the back button. Below is the code I have tried for my log out page: protected void Page_Load(object se ...

How can I dynamically update an img src using JavaScript on a PHP webpage?

I have a PHP page where I display image thumbnails. I am trying to implement a feature where the thumbnail expands in another image on mouseover. Here is the PHP code snippet: echo "<tr><td><a href='$imgrow[location]' target=&ap ...

How to properly implement HATEOAS in the response for user account creation

I have developed a REST API in Node.js that implements HATEOAS. Users must first create an account before gaining access to most of the API's functionality. The process involves registering an account with login credentials, logging in to receive an ...

Execute the function as soon as the variable is declared

Currently, I am immersed in a project that involves a significant amount of user-generated code (influenced by this video ). My objective is to evaluate a portion of user-input code using eval(), and trigger a function every time a variable is defined, two ...

When using Node.js and geth together, running JavaScript code may lead to the creation of zombie processes, causing the

Currently, I am utilizing a JavaScript code that connects to the web3 package on Ethereum's JSON RPC API. This code is designed to iterate through each transaction in an incoming block. If the transaction involves an internal wallet, it sends the rele ...

Is it possible to send a URL with a specific translation using jquery i18n?

Here's my dilemma: The URL I am working with is: www.example.com By default, the translation of this page is set to Japanese. However, when a user clicks on a button, the page translates to English but the URL remains as www.example.com. Is there a ...

Attempting to dynamically update a dropdown select element without reloading the page using pure Vanilla JavaScript

Having trouble updating a dropdown dynamically in Vanilla Javascript without page refresh? I need to create an owner and add it to the dropdown menu, but currently, I have to reload the page to see the update. Can you help me achieve this without using jQu ...

Implementing material-ui Snackbar as a global feature: a step-by-step guide

Currently, I'm in the process of building my react application using material-ui's Snackbar feature. With a plethora of components in my project, I prefer not to include <Snackbar/> in every single one of them. Is there a method to develop ...

What is the best way to show the user profile on a Forum?

I am struggling to figure out how to display the username of a user on my forum page. I currently only have access to the user's ID and need help in extracting their name instead. It seems that I lack knowledge about mongoose and could really benefit ...

Retrieving information within the iteration

I am facing an issue with connecting to an external server named Pexels in order to retrieve photos from node.js. The problem seems to be related to JavaScript, as Pexels limits the user to download up to 40 pictures per page. https://api.pexels.com/v1/cu ...

Which is more effective: coding with just plain JavaScript and CSS, or utilizing frameworks?

As a student, is it more beneficial to focus on utilizing pure JavaScript & CSS or frameworks? And which approach is best suited for the professional field? ...

Error: JSON key data not present in rendering

Here is a JSON string I am working with: {"{\"nodeName\":\"abc\"}":[{"url":"abc","status":true},{"url":"abc","status":true}]," {\"nodeName\":\"pqr\"}":[{"url":"abc","status":true},{"url":"abc","status":true}]} ...

How can I insert my JavaScript functions into the JSF event queue for processing?

Is there a way to tap into the default JSF ajax(JS) event queuing system in order to execute events sequentially? I am attempting to align my JS events with this queue. Is there a global variable that can facilitate this synchronization? ...