tags:

views:

657

answers:

4

Hello,

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.

+1  A: 

The data returned is a string, and cannot be found in the dom via jQuery until it's actually in the DOM. You will need to parse this string and pull out the data you require, or edit it after you insert in the DOM.

Jay
Thanks for the vote up Jay. I see someone voted yours down, I wish they'd give a comment when they did that.
darkporter
A: 

Jay's answer is right - you will need to insert the HTML data into the DOM first (or parse the string, which seems cumbersome). What you can do is append the data to a hidden DIV, modify it, then copy the data to a different DOM element or just show the DIV

pygorex1
+6  A: 

You don't need a hidden DIV. If you want to convert an html string to a DOM fragment, simply call jQuery on it. In your example:

success: function(data) {
    var jqObj = jQuery(data);
    jqObj.find("li:last").remove();
    $("#id").empty().append(jqObj);
}

Some IE considerations though:

  • If your data is large, jQuerifying it in-place is slow in IE (at least with jQuery 1.2.6). In that case you may want to create a container for it like var div = jQuery("<div/>"); div.html(data); then manipulate it there before doing $("#id").html(div.html()).
  • If your data has invalid HTML (unclosed tags, etc) you may get weird failures in IE. Just make sure the html is well-formed.
darkporter
+1 didn't realise you could do this, very nice.
Jay
awesome! thx alot ;-D.
Marcel
They down voted everyone on the page (if it was the same person). Very strange as none of the answers are actually incorrect/bad practice or offensive.
Jay
+5  A: 

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

Dave Ward