...

/

DELETE Request to REST API

DELETE Request to REST API

Learn to delete a lecture post using the WordPress REST API.

On the Lecture Notes page, every lecture post has a Delete button associated with it. We will create an event listener to respond to a click event on it.

With the Excellence folder open in VS code, access the terminal by clicking the "View" option and choosing "Terminal". Run the start script using the npm run start command. The start script will watch for any changes in the code and recompile it.

Click event on Delete button

To add an event listener to the Delete button, first we will select all Delete buttons in the deleteButtons variable using the querySelectorAll method. We gave the Delete button a class of delete-lecture (in page-lecture-notes.php).

constructor(){
//...
this.deleteButtons = document.querySelectorAll(".delete-lecture");
//...
}
Selecting all Delete buttons

The deleteButton variable is a NodeList of all elements with the class delete-lecture. In the events method, loop through the NodeList and attach an event listener to each item. When a click event occurs, the callback method deleteLecture is called. This method displays a message on the console.

To check the message on the console, we can right click the page and click the "Inspect" option. From the panel that opens up, choose the "Console" option.

class Lecture{
constructor(){
this.deleteButtons = document.querySelectorAll(".delete-lecture");
this.events();
}
events(){
this.deleteButtons.forEach(button => {
button.addEventListener("click", this.deleteLecture.bind(this));
});
}
//methods
deleteLecture(){
console.log("The Delete button was clicked.");
}
}
deleteLecture() callback method

The addEventListener method changes the value of this keyword from the global object to the element that ...