Alex Rivera | Logout

Manipulating the "data" from $.ajax success: function(data) {

Asked 2009-12-10T01:28:56.240
22

i have this and a simple question to it.

$.ajax({
    type: "POST",
    url: "/",
    data: $(".form").serialize(),
    dataType: "html",
    success: function (data) {
        $("#id").html(data);
    }
});

Inside "data" is some html I am inserting into the DOM. Thats no problem. But I want to manipulate the "data" before doing so. How can I do that? For example there are some li elements in "data". How would I for example delete the last li element out of the "data" string before inserting it into the DOM?

I tried something like

$(data li:last)remove();

...but that didnt work.

Thanks for your help.

Edit
Report

1 Answer

8

You can create a jQuery object from arbitrary HTML, e.g.:

$('<ul><li>Item</li></ul>');

So, you could do something like this:

success: function(data) {
  var $list = $(data);

  $list.find('li:last').remove();

  // Do something with $list here, like append().
}

Here's a working example you can play around with on JS Bin: http://jsbin.com/ejule3/edit

answered 2009-12-10T02:13:50.870

Your Answer