I'm trying to put buttons on my page that delete posts the user has made, like on a social network. My page's javascript looks like this and I'm getting the error "Uncaught TypeError: Cannot read properties of undefined (reading 'remove')"
<script>
const deleteBtn = document.querySelectorAll(".ri-close-line");
const postDelete = document.querySelectorAll(".new-post");
for(var i = 0; i < postDelete.length; i++) {
deleteBtn[i].addEventListener("click", function () {
postDelete[i].remove();
});
}
</script>
This is the ejs code:
<% if (locals.PostArray) { %>
<% for (let i = 0; i < PostArray.length; i++) { %>
<% if (locals.createPost) { %>
<div class="container-new-post">
<div class="new-post post">
<div class="image-profile-new-post-box">
<img src="/images/profile.jpg" alt="Profile image" class="image-profile-new-post">
</div>
<div class="text-line-new-post">
<div class="first-line-new-post">
<div>
<span class="profile-name-new-post"> XXX </span>
<span class="profile-user-new-post"> XXX </span>
</div>
<div class="incons-new-post">
<i class="ri-pencil-line"></i>
<i class="ri-close-line post"></i>
</div>
</div>
<div class="text-new-post">
<form action="/text" method="POST">
<input type="text" name="text-post" value="<%= PostArray[i] %>" class="text-post-edit" contenteditable="false">
</form>
</div>
<div class="last-line-new-post">
<div class="incons-new-post" id="incons-new-post1">
<i class="ri-chat-3-line"></i>
</div>
<div class="incons-new-post" id="incons-new-post2">
<i class="ri-repeat-line"></i>
</div>
<div class="incons-new-post" id="incons-new-post3">
<i class="ri-heart-line"></i>
</div>
<div class="incons-new-post" id="incons-new-post4">
<i class="ri-bar-chart-grouped-line"></i>
</div>
<div class="incons-new-post" id="incons-new-post5">
<i class="ri-save-3-line"></i>
<i class="ri-share-line"></i>
</div>
</div>
</div>
</div>
<% } %>
<% } %>
<% } %>
And this is my node.js code:
import express from "express";
import bodyParser from "body-parser";
const port = 3000;
const app = express();
var userIsAuthorized = false;
var createPostArray = []
let data0;
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));
function passwordCheck(req, res, next) {
if (req.body.password === "XXXX" && req.body.email === "XXXX") {
userIsAuthorized = true;
}
next();
}
app.use(passwordCheck);
app.get("/", (req, res) => {
res.render("login.ejs")
});
app.post("/check", (req, res) => {
if(userIsAuthorized === true) {
res.redirect("/home");
} else {
res.redirect("/");
}
});
app.get("/home", (req, res) => {
res.render("index.ejs", {
createPost: data0,
PostArray: createPostArray,
})
});
app.post("/post", (req, res) => {
const textPost = req.body["createPost"];
data0 = textPost;
createPostArray.push(textPost);
res.redirect("/home");
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
I tried using the for, if property, but it always gives the same problem.