I have been working on a Django project where I've created several HTML divs. My goal is to add a single button to each div. https://i.sstatic.net/DEIqL.png
In the image provided, you can see a div with the class card-footer
that I created using a Django for loop. I intend to include a blue colored like button in each of these divs through javascript. However, as shown in the image, the button is only being added to one div.
Below is a snippet of my HTML template:
<div id="posts" class="card">
<ul class="card-body">
{% for posts in page_view %}
<li class="card">
<div class="card-header bg-success">
<h5 class="card-title"><a class="text-light" style="text-decoration: none;" href="{% url 'profile' posts.user.id %}">{{ posts.user }}</a></h5>
<h6 class="card-subtitle text-light">{{ posts.timestamp }}</h6>
</div>
<div class="card-body">
<h3 class="card-text">{{ posts.post }}</h3>
</div>
{% include 'network/like.html' %}
</li>
{% empty %}
<h6>No post availabel đ</h6>
{% endfor %}
</ul>
</div>
Here is the content of my network/like.html
file:
<div class="card-footer">
<form action="{% url 'likepost' posts_id=posts.id %}" id="likeform" method="POST" style="display: inline;">
{% csrf_token %}
<button id = "like" class="btn btn-link" type="submit">Like</button>
</form>
<small id="num_of_likes">{{ posts.likepost.all.count }}</small>
{% block script %}
<!-- <script>
let posts_id = "{{ posts.id }}";
</script> -->
<script src="{% static 'network/controller.js' %}"></script>
{% endblock %}
<button class="btn btn-link" style="text-decoration: none;">Comment</button>
<a href="{% url 'postpage' id=posts.id %}" class="btn btn-link" style="text-decoration: none;">View Post</a>
{% if request.user.id is posts.user.id %}
<a href="{% url 'editpost' id=posts.id %}" class="btn btn-link" style="text-decoration: none;">Edit</a>
{% endif %}
</div>
The issue arises when trying to add a like button within the card-footer
div to all elements but only getting added to the first one. Here is my complete js code:
document.addEventListener("DOMContentLoaded",function(e){
e.preventDefault()
const likebtn = document.createElement('button');
likebtn.setAttribute('class','btn btn-primary');
likebtn.setAttribute('id','likebtn')
document.querySelector('.card-footer').appendChild(likebtn);
document.querySelector('#likebtn').innerHTML = "Like";
})
function like_function(likepost){
document.createElement('button').innerHTML = "Love";
fetch(`/likepost/${posts_id}`)
.then(response => response.json())
.then(result => {
console.log("Updated.");
if(result.is_like){
document.querySelector('#like').innerHTML = "Unike";
}
else{
document.querySelector('#like').innerHTML = "Like";
}
})
location.replace("http://127.0.0.1/")
}
As a newcomer to javascript, I'm struggling to identify what's causing this issue. Any insights or advice would be greatly appreciated!