Function activated when adding an event listener

Retrieve information from page.html:

<div id="46" class="cont-text-profile">
<span class="data"># March 4, 2021, 5:17 p.m.</span>
<p class="text">Tutto ok!!!!!!!111111111222222233333334444444</p>
<div class="edit"><a id="edit-46" href="javascript:void(0)" class="edit_post">Edit</a></div>
<div id="like" class="like"><a id="ilike-46" href="javascript:void(0)"  class="like_post ">Like it?</a> (<span id="nlike-46">1</span>  like)</div>
<div class="spacing"></div>
</div>  

View script.js data

document.addEventListener('DOMContentLoaded', function() {

    const edit=document.getElementsByClassName('edit_post');
    if (edit != null){
        for (const ele of edit)
        {ele.addEventListener('click',edit_post)}
    }

});

function edit_post(e){
    const id=parseInt(e.target.id.split('-')[1]);
    const parent=document.getElementById(id);
    if (parent != null){
      const p=parent.querySelector('p')
      const form=document.createElement('TEXTAREA');
      form.id='d_textarea_'+id;
      form.maxLength=260;
      form.cols=52;
      form.rows=4;
      form.required;
      form.classList.add('d_textarea');
      form.value=p.innerHTML;
      parent.replaceChild(form,p);
      const all_edit_a=document.getElementsByClassName('edit_post');
      for (let a of all_edit_a){
        if (a.id == e.target.id){
          e.target.innerHTML='Save';
          e.target.addEventListener('click', save_post);
          continue;}
        a.removeEventListener('click',edit_post)
        a.addEventListener('click', alert)
      }
      
    }
  }

  function save_post(e){
    const id=parseInt(e.target.id.split('-')[1]);
    const textarea = document.getElementById('d_textarea_'+id);
    const edited_post = textarea.value;
    if (edited_post == ''){
      alert('The post cannot be empty, please write something.');
      return false
    }
    fetch('/modify/' + id, {
      method : 'PUT',
      headers: {'Content-Type': 'text/html'},
      body : edited_post
      })
        .then(response =>{
          if (response.status != 200)
          {
            alert('Error. Please refresh page e retry. Err : '  + response.status);
          }else{
            const all_edit_a=document.getElementsByClassName('edit_post');
            for (let a of all_edit_a){
              if (a.id == e.target.id){
                a.removeEventListener('click', save_post);
                a.addEventListener('click',edit_post);
                a.innerHTML='Edit';
                continue;}
              a.removeEventListener('click', alert);
              a.addEventListener('click',edit_post);            
            }
            const parent=document.getElementById(id);
            const p=document.createElement('p');
            p.classList.add('text');
            p.innerHTML=edited_post;
            parent.replaceChild(p,textarea);
  
          }
        })
        .catch(error => {console.log('Error while processing the request:' , error);
    })
  }

  function alert(){
    alert('Save changes before leave please.');
  }

The function is operational but an error message is displayed:

scripts.js:46 Uncaught TypeError: Cannot read property 'innerHTML' of null at HTMLAnchorElement.edit_post

whenever I press "Save" (and subsequently trigger the edit_post handler again) It seems that the "edit_post" handler gets called after a.addEventListener('click',edit_post);

Answer №1

First of all, it's important to note that attempting the following action is not recommended:

function alert(){
    alert('Please save any changes before exiting.');
}

Secondly, consider utilizing the defer attribute instead:

<script src="main.js" defer></script>

as opposed to

document.addEventListener('DOMContentLoaded', <...>);

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

The typical number of keys in a ChartJS graph is 2

Currently, I am utilizing ChartJS for a project that displays user-added records such as weight and heart rate for tracking purposes. I have encountered an issue where if a user adds two slightly different value records for the same day, it results in both ...

Sometimes the AngularJS scope is refreshed only intermittently

I am encountering an issue with a list of cards retrieved from an API and displayed in a table using ng-repeat. The problem arises when I attempt to delete a card - sometimes it remains in the view, while other times it disappears as expected after confirm ...

Using Javascript to Treat an HTML Document as a String

Check out the complete project on GitHub: https://github.com/sosophia10/TimeCapsule (refer to js/experience.js) I'm utilizing JQuery to develop "applications" for my website. I'm encountering a problem where I can't locate the correct synta ...

Session authentication mechanism designed to remain active only as long as the browser tab is open

Imagine you are developing a front-end application that utilizes a third-party API for authentication, with a successful authentication resulting in a JSON web token. What strategies would be most effective for storing this token and establishing a user s ...

How to define an index signature in Typescript that includes both mandatory and optional keys

I am on a quest to discover a more refined approach for creating a type that permits certain keys of its index signature to be optional. Perhaps this is a scenario where generics would shine, but I have yet to unlock the solution. At present, my construc ...

Modify the `<link>` tag using the `onclick` function in JavaScript

I want to switch up the site's style with just a click on an icon <head> <meta charset="utf-8"> <link rel="stylesheet" href="styled.css" id="styles"> </head> Everytime I try to tackle th ...

In PHP, a boolean variable will not display on the webpage when echoed

I am facing an issue with my PHP code where certain variables are not being echoed properly in the generated JavaScript. The code is designed to check if specific values are assigned in the $_GET global array and assign default values if they are not prese ...

The event emitted doesn't appear to be caught by EventBus.$on in Vue.js

Currently trying to trigger an event from router.beforeEach and listening for it in another component. Although the vue devtool confirms that the event is being triggered, my component seems unable to capture it. Thank you for your help. This is how I dec ...

What is the best way to prevent a React app's scripts from loading on browsers that do not support them?

My current project makes use of create-react-app, where the React script main.js is loaded at the bottom of the <body/> tag. However, it crashes on unsupported browsers upon loading. Above the main.js script block, there is another <script> th ...

Utilize express.static to showcase and fetch HTML content before serving JavaScript files

I'm having trouble getting my home.html file to display properly on the browser when I'm using express.static. Here is how my directory and file layout are structured: dir main -server.js dir subMain dir routing -routes.js ...

My goal is to programmatically eliminate captcha from a website

Is there a way to automatically remove capture from a Page using javascript (Greasemonkey)? The page's HTML structure seems complex, so any suggestions on how to achieve this would be greatly appreciated. <div class="wrapper"> <d ...

What should you do when the server is taking a while to respond?

I am in the process of creating a webpage that involves interactions between users, and I could use some guidance. Let's consider this hypothetical scenario: Client A visits a 'public' webpage and clicks a button. Client A then waits for a ...

Struggling to verify HTTP GET Request in Node.js with Express.js authentication

Attempting to send data via a Get Request, the recipient is utilizing basicauth-middleware for authentication purposes. Authentication through the browser and within the original program (without sending data) is successful, with a confirmation message ind ...

Having trouble with your Angular routes tutorial?

I'm currently working on Google's Angular tutorial log (with different names for the necessary items), and I can't seem to get the routing to function correctly. If I remove the "#" from the hrefs, I end up with a "Cannot GET" error. But eve ...

Is there a way to retrieve the JavaScript constructor object by passing it as a parameter in an IIFE function?

In my first method, I have successfully created an object constructor called Person. Inside this constructor, I used an IIFE function expression which is functioning correctly. The property inside this function of Person is accessible! var Person = fun ...

The dynamics of Express.js functionalities

I am seeking to better understand how flow functions within an Express app using Routes, with the following set of Routes: app.use(require('./routes/reportsRouter')); app.use(require('./routes/crewsRouter')); app.use(require('./ro ...

The FlatList component with a specified number of columns is failing to display the desired

Hey guys, I have a food list data stored in JSON format as shown below: [ { "id": 0, "key": " Viande hachee", "checked": false, "image": "https://i.imgur.com/RuVD8qi.png " }, { "id": 1, "key": " Escalope pane", "check ...

How can you iteratively filter an array using JavaScript?

My goal is to create a function that can filter an array based on one or multiple conditions. Let's examine this example data and filter criteria: var data = [ {company: "Acme", fiscal_period: '01-2019', value: 10}, {company: "Acme", f ...

Buttons and JavaScript: A Comprehensive Compilation

I'm facing an issue with my HTML buttons and JavaScript. When a button is clicked, an AJAX call should be triggered to display data. However, JavaScript seems unable to detect the button. Below is the HTML code: <ul> <li><input ...

Accessing JSON object with Javascript

I've been struggling with this code snippet and despite looking at similar posts, I can't seem to get it right. var obj2 = JSON.parse('{"venue_data": {"venue_id":"25", "description":"Space Cafe", "venue_type ...