Ways to extract the id after clicking

In my code, I have a query called snapshot.forEach that functions similarly to a for loop in looping through all of my Firebase data and displaying it with a div tag containing a click event. When another user clicks on this div tag, the event will retrieve the document in Cloud Firestore with the corresponding id. However, I am currently seeking a method to extract this id from the triggering div tag.

db.collection("posts")
    .get()
    .then((querySnapshot) => {
        querySnapshot.forEach((doc) => {
        postData = doc.data()
        var wrapper = document.createElement('div')
        wrapper.classList.add('wrapper')
        wrapper.setAttribute('id',postData.title);
        var content = document.createElement('div')
        content.classList.add('content')
        content.setAttribute('id',postData.id);
        var title = document.createElement('h1')
        title.classList.add('title')
        var introduction = document.createElement('p')
        introduction.classList.add('introduction')
        title.innerHTML = postData.title
        introduction.innerHTML = postData.introduction
        postCollection.appendChild(wrapper)
        wrapper.appendChild(content)
        content.appendChild(title)
        content.appendChild(introduction)
        content.onclick=function(event){
      profilePage.classList.add('hide')
      forumePage.classList.add('hide')
      postPage.classList.add('hide')
      postComment.classList.remove('hide')
        }
            console.log(doc.id, " => ", doc.data());
        });
    })

https://i.stack.imgur.com/tL1st.png

Answer №1

I believe this response should provide some clarity to your inquiry, or at least my interpretation of it

db.collection('posts')
  .get()
  .then ( querySnapshot =>
    {
    querySnapshot.forEach( doc =>
      {
      let postData = doc.data()
        , wrapper  = document.createElement('div')
        , content  = document.createElement('div')
        ;
      wrapper.className = 'wrapper'
      wrapper.id        = postData.title
      content.className = 'content'
      content.id        = postData.id
      content.innerHTML = `
        <h1 class="title">${postData.title}</h1>
        <p class="introduction">${postData.introduction}</p>`

      wrapper.appendChild(content)
      postCollection.appendChild(wrapper)

      content.onclick = event =>   // in case of way 1 you need to use Arrow function
        {
        profilePage.classList.add('hide')
        forumePage.classList.add('hide')
        postPage.classList.add('hide')
        postComment.classList.remove('hide')
        console.log(content.id)               // way 1
        console.log(event.currentTarget.id)   //  way 2
        }
      console.log( doc.id, " => ", doc.data())
      })
    })

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

Leveraging Webpack and Jest for seamless module importing in a development project

I've been working on a Node project and utilizing imports and exports extensively. To package the frontend code, I opted for Webpack. However, it seems to require running as common JS. Moreover, Jest is being used in my project, which led me to spec ...

What could be causing the issue with "class not being recognized as a constructor" error that I am encountering?

When attempting to create an instance from modules in routing, I consistently encountered the error message "class is not a constructor." Below is the code snippet: export class Modules{ modules : object = { masterdata : MasterdataModule, shop : ...

The Safari browser is unable to provide the country name in the geolocation response

My geolocation feature for displaying country names is functional in Chrome and Firefox, but not in Safari. How can I troubleshoot this issue? Javascript: $.get("http://freegeoip.net/json/", function (response) { $("#ip").html("IP: " + response.ip); ...

Struggling with dynamic values and regex while utilizing HTML template strings. Need help overcoming regex challenge

Feeling stuck and seeking advice on improving regex usage. For a one-time substitution, the code below works for replacing a single element like -link-. var testHtmlStr = '<tr>' + '<td class="eve"><div class= ...

Utilizing an npm Package in Laravel - Dealing with ReferenceError

I'm having trouble with the installation and usage of a JS package through npm. The package can be found at . First, I executed the npm command: npm install --save zenorocha/clipboardjs Next, I added the following line to my app.js file: require(& ...

How about generating a promise that serves no real purpose and simply resolves?

Managing promises in Node.js can be a bit tricky, especially when dealing with different scenarios. One common use case is catching the last promise result and formatting it accordingly. req.resolve = (promise) => { return promise.then(() => { ...

Leveraging shadow components with the Next.js pages directory

I am facing an issue with getting a simple shadcn button to work because I am unable to import the button. Although I am using nextjs 13, I am still utilizing the pages directory. Below is the process of how I installed shadcn. Here is the installation co ...

Using Jquery to add a list after parsing JSON data stored in localStorage

I've been stuck on this issue for quite some time now. The problem I'm facing involves checking the localStorage to see if there's a cached JSON string available. If there is, I load it and convert it back into a JSON object. If not, I make ...

retrieve an item that lacks a definitive value

Here's an object I have: Obj = { foo: false, bar: true, private: { something: 'else' } } Now, I'm trying to return this object without the private part. Since the private part is used elsewhere and cannot be spliced out, I ...

Rendering on the server with React, React-Router, and Express

I'm currently in the process of setting up server-side rendering for my react application and I'm utilizing the fantastic react-router module to enable it to manage non-js scenarios (such as certain crawlers or users with javascript disabled). Ne ...

Tips for transmitting form information in a fetch call

As I was developing a nodejs server, I encountered an issue with the POST call that involves sending form input data to a remote server. Despite everything else working fine, the form data was not being received by the server. Below is the code snippet in ...

Updating or deleting query strings using JavaScript

My URL is structured as follows: http://127.0.0.1:8000/dashboard/post?page=2&order=title I am seeking a way to eliminate the query string ?page={number} or &page={number} Due to my limited knowledge of regular expressions, I am wondering if there ...

HTML background image not displaying in JSPDF addHTML function

I am facing an issue with my HTML page where the background image in the header section is not displaying when converting the page to PDF using jspdf. Although all the other content appears correctly, the background image seems to be missing. You can vie ...

Exploring Keypress events with Dojo's 'on' module

Recently, I've started utilizing Dojo's latest on module for event handling. It has been working well so far, but a new issue has cropped up. Specifically, when using the keypress event, I am unable to retrieve the character value (such as "2" or ...

utilizing geographical coordinates in a separate function

I have a program that enables users to access the locations of communication cabinets. I am attempting to utilize html5 to transmit latitude and longitude information to a php script (geo.php) in order to update the database record with map coordinates. Ho ...

JavaScript and Angular are used to activate form validation

Update: If I want to fill out the AngularJS Forms using the following code snippet: document.getElementById("username").value = "ZSAdmin" document.getElementById("password").value = "SuperSecure101" How can I trigger the AngularJS Form validation befo ...

What is the best way to implement an event listener for every button in a table row outcome?

I have a Rails application where I am populating a table using an @results variable, with each row representing a @result. My goal is to have buttons associated with each @result, and I'm attempting to use a JavaScript event listener for each button a ...

What could be the reason behind receiving a 406 Not Acceptable status at the client side from the server, and why is my Spring controller not being triggered?

Here is the code for an AJAX GET request: $("#tabsss2").click(function tab1() { $.ajax({ type: "get", traditional: true, dataType: 'json', url: "DataGridServlet.htm", cache: false, ...

Tips for converting ActiveRecord hierarchy into a JavaScript array

Currently, I am in the process of incorporating a treeview feature into my institution model within my rails application. To accomplish this, I have integrated the ancestry gem into my model successfully and included the treeview component into my view wit ...

Group the JSON data in JavaScript by applying a filter

I have a specific json object structure with keys cgi, tag and name, where the cgi key may be repeated in multiple objects. If any cgi has the tag 'revert', then that particular cgi should not be returned. [ { "cgi": "abc-123 ...