Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - modify HTML string

Tags:

html

jquery

ajax

Could someone tell me how I can modify the html before I insert it into the document?

This is an AJAX call:

url: "http://localhost/cart/public/admin/album",
success: function(html) {

This is the result of the AJAX call:

<div class="main-content slide-in">
    <h1>Create Album</h1>
    <div class="inner">
    </div>
</div>

All I want to do is change the color of the h1 tag. I have added this code

url: "http://localhost/cart/public/admin/album",
success: function(html) {
    $(html).find('h1').css('color','red');
    $('aside').after(html);

However this has no effect. The jQuery selector does seem to be working though.

url: "http://localhost/cart/public/admin/album",
success: function(html) {
    $(html).find('h1').css('color','red');
    console.log($(html).find('h1').length);
    $('aside').after(html);

Using console.log correct outputs 1. So it is finding the h1. For some reason though the css style isn't being applied.

I am bit stuck. Am I missing a step?

like image 580
Computer User Avatar asked Oct 26 '11 14:10

Computer User


2 Answers

Looks like you're changing the color and then adding the unchanged string to the DOM. Try this:

success: function(html) {
    var $html = $(html);
    $html.find('h1').css('color','red');
    $('aside').after($html);
like image 106
Tetaxa Avatar answered Sep 28 '22 19:09

Tetaxa


The accepted answer here actually wasted quite a lot of my time. At least it isn't generic. This is what figured out after sometime.

$.ajax({
  url: "http://localhost/~yoelusa/the-url-of-your-string.html",
  success: function(htmldata) {
    var $html = $("<div/>").append( htmldata );
    // make your changes on the html string, see some example bellow relevant to my htmlstring
    $html.find('#left').html("");
    $html.find('#right').html("");
    $html.find('.commentlist').remove();
    // when you are ready to insert your string somewhere call the html() function, in my example I inserted it in an iframe
    $("iframe").attr("srcdoc", $html.html() );
  }
});
like image 40
Yoel Garcia Avatar answered Sep 28 '22 18:09

Yoel Garcia