jQuery - replace content on click

Hello

I would like to know how I can do this on jQuery.
How can I replace content with something else when I click on the content or when I click on a link.

In the head section of your HTML, you bind an event handler to the click action of an element, and then take the appropriate action within the event handler.

Let’s say that the thing you click has an id of “button”, the element you want to change the content of has an id of “content”, and the new content you wish to put into it is “new content”. Then you would do something like this:


$(document).ready(function() {
  $("#button").click(function() {
    $("#content").text("new content"); // Use .html() if the content has HTML in it
  });
});

This simply replaces the content of an element when something else is clicked, which I’m not sure is entirely what you want since I’d imagine you’re after something a little more complicated (maybe retrieving the data from a server or something?), but it’s a start. If the element to be clicked and the element to have its content replaced are one and the same, then just take the code above and change “Content” to “this” (without the quotes).

Also, if it’s a link that you’re clicking on, the function you pass to .click() should look like this:


function(e) {
// ... code to replace the content ...
e.preventDefault(); // Prevents the browser from trying to follow the link
}

Hi, thank you for your response.

I understand that it replaces the content within the div. Is it possible to replace the div with another div?

jQuery has a built in method to do this called .replaceWith()