Reputation: 546
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?
Upvotes: 9
Views: 9772
Reputation: 173
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() );
}
});
Upvotes: 3
Reputation: 1852
Try this:
$(html).find('h1').css('color', 'red').parent().insertAfter('aside');
Upvotes: 2
Reputation: 4403
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);
Upvotes: 17
Reputation: 46047
Try adding !important
to the css style:
$(html).find('h1').css("color", "red !important");
Upvotes: 0