Search code examples
javascripthtmldjangocustom-data-attribute

Uncaught TypeError: Cannot read property 'style' of null when using data-SOMETHING attribute to pass parameter to JavaScript function


I'm new to coding and I'm trying to hide a paragraph using JavaScript.

This is my HTML

{% for post in posts %}

    <div class="container p-3 my-3">
        <div class="card">

                    <div class="card-block px-1">

                        <h4 class="card-title">
                            <a href="{% url 'profile' post.user.id %}">{{ post.user }}</a>
                        </h4>

                        <p class="card-text" id="{{ post.id }}">{{ post.content }}</p>

                        <textarea style="display: none;" id="edit-view">{{ post.content }}</textarea>

                        <p class="card-text" id="time">Posted on: {{ post.timestamp }}</p>

                        {% if post.user == request.user %}
                        <button type="button" class="btn btn-primary" id="edit-btn" data-text="{{ post.id }}">Edit</button>
                        {% endif %}

                        <button type="button" class="btn btn-primary" id="save-btn" style="display:none;">Save</button>

                        <p class="card-footer">{{ post.like }} Likes</p>

                    </div>

            
        </div>
    </div>

{% endfor %}

Looking at the source code I could verify that the post.id context is correctly displayed in both the data-text attribute and the id of the paragraph I want to hide.

This instead is my JavaScript function (which I have in a separate js file):

function edit(text) {

    // hide content
    document.querySelector(`#${text}`).style.display = 'none';
}

I'm calling the function after loading the DOM and applying and event listener to all buttons with id of edit-btn:

document.addEventListener('DOMContentLoaded', function() {
        
 // Adding event listener
 document.querySelectorAll('#edit-btn').forEach(function(button) {
   button.onclick = function() {
   console.log('Button clicked!')
   edit();
   }
  });
});

Nevertheless I get the above error, as if the parameter is not being passed to the function?

Any help is really appreciated.

P.S. hiding the paragraph is just the first step of the edit function. I should then replace it with a textarea, populated with the paragraph's content, where the user can edit and then save the content of their post. Unfortunately, I've been stuck at this first step for some time now.


Solution

  • You have to pass post.id to edit() function as below:

    button.onclick = function(event) {
      const editBtn = event.target;
      const postId = editBtn.getAttribute('data-text');
      edit(postId);
    }