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

It is impossible to alter the data contained within the input box

Objective: Upon clicking a button to display the modal, the selected data (first and last name) should be inserted into an input box and editable. The user should be able to modify the data. Issue: The data entered into the input box cannot be edited ...

Leveraging AngularJS and ng-map to incorporate interactive dynamic heatmap displays

Greetings everyone! I am completely new to frontend development and have embarked on my first journey with AngularJS. I must admit, it's quite challenging and I'm still trying to wrap my head around how it all works. Currently, I'm working o ...

Strip away double quotation marks from object attributes except those beginning with a number

I've searched extensively and reviewed various Q&A forums, but I haven't encountered a scenario quite like this. Here's an example of the object I'm working with: props: { "label": "1rem", "text3": "1rem", "text2Button": "1re ...

How to successfully load the google-map-react library

After installing the google-map-react library locally in my app, I verified that it is listed in my package.json under dependencies. The corresponding folder also exists in the node_modules directory. However, when attempting to reference the component con ...

What is the best method for utilizing dynamically assigned keys within a JSON object?

I am currently working with Rhino and I need to find a way to utilize a variable in order to define the key of a map. Here's an example of what I'm trying to achieve: var name = "Ryan"; var relationshipType = "brother"; var relatedName = "David" ...

Adjust the size of the iframe image to fit seamlessly within the design

Is there a way to adjust the size of the image on the right without altering the layout design? The current GIF is 500x500px, but it is only displaying as 100x100px. Any assistance would be greatly appreciated! To see what I currently have (Demo with code ...

Utilize AngularJs and JavaScript to upload information to a JSON file

Exploring the realm of Angular JS, I am on a quest to create a CRUD form using AngularJs and Json with pure javascript without involving any other server side language. The script seems to be functioning well but is facing an obstacle when it comes to writ ...

Develop a novel function

I am working on a new Order page where users can select a category, then a service, and fill out the quantity field for their order. I have an idea to create a function using @if and @else statements. In this function, I want to display the quantity fiel ...

After logging in successfully, the React app needs a hard refresh to update the

I'm encountering a debugging challenge and would appreciate any assistance from the community. I've been working on my first React app and successfully implemented a Login feature, but after a user logs in, they have to hard refresh their browser ...

Update nested child object in React without changing the original state

Exploring the realms of react and redux, I stumbled upon an intriguing challenge - an object nested within an array of child objects, complete with their own arrays. const initialState = { sum: 0, denomGroups: [ { coins: [ ...

Chrome does not support top.frames functionality

I have three HTML pages: main.html, page1.html, and page2.html. I am displaying page1.html and page2.html within main.html using the code below. <!DOCTYPE html> <html> <frameset frameborder="1" rows="50%, *"> <frame name="f ...

What could be causing my textarea-filling function to only be successful on the initial attempt?

Programming: function updateText() { $("body").on("click", ".update_text", function(event) { $(this).closest("form").find("textarea").text("updated text"); event.preventDefault(); }); } $(document).ready(function() { updateText(); }); H ...

Tips for creating a zoomable drawing

I have been working on this javascript and html code but need some assistance in making the rectangle zoomable using mousewheel. Could someone provide guidance? var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var width ...

`I'm having difficulty transferring the project to Typescript paths`

I posted a question earlier today about using paths in TypeScript. Now I'm attempting to apply this specific project utilizing that method. My first step is cloning it: git clone <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cf ...

Having an issue with displaying the country name and country code in a table using the Angular7 custom pipe

country code: "ab", "aa", "fr", ... I need to create a custom pipe that will convert a countryCode into a countryName, such as: "ab" → "Abkhazian", "ch" → "Chinese", "fr" ...

Efficiently sorting items by category name in PHP with Ajax

Currently, I am working on a functionality that involves two dropdown lists. The first one, located at the top, is for selecting a category of meals. Each option in this dropdown has an associated id_cat value. <option value="1">Pâtis ...

Verify if an express module has a next() function available

Is there a method to check if there is a function after the current middleware? router.get('/', function(req, res, next){ if(next){//always returns true } }); I have a function that retrieves information and depending on the route, thi ...

Showing JSON object in an Angular 2 template展示JSON对象在模

When I execute the following code: stanservice.categoryDetail(this.params.get('id')) .then((data) => { this.category = JSON.stringify(data.res.rows[0]); console.log(JSON.stringify(data.res.rows[0])); }) .catch((error) => { ...

Identifying Master Page Controls Post-Rendering

Within my asp.net projects, I have noticed a discrepancy in the control id on the master page's Contentplaceholder1. On my local server, the id appears as "ctl00_Contentplaceholder1_control" after rendering. However, when the application is deployed t ...

In order to enhance your programming skills, avoid hard coding functions and ensure that data is returned after binding changes

I am trying to create a method where I can provide a DOM as a parameter and retrieve data from image_preview. The goal is to make image_preview reusable instead of hardcoding it inside the function. Additionally, I want to separate image_preview.model() an ...