0

Actually it could happen that's the title it's not exactly correct, so sorry. My problem is the following. I have a variable (what contains html), what it get from ajax response and i would like to add new attribute a few element. And after it insert to the dom.

For example, here this:

ajaxString  = "<b>asd</b>";
replaced    = $("b", $(ajaxString) ).css('background','#ff0000');
$("body").html(replaced);

But it's doesn't work. I hope, somebody have an idea!

Thanks for the Help!

Mate
  • 61
  • 4

3 Answers3

0

You can create the element in a jQuery object first, then amend its attributes before appending it. Try this:

$("<b>asd</b>").css('background', '#ff0000').appendTo('body');
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
0

This can be done using a virtual element:

var ajaxString = "<b>asd</b>",
  virtualDiv = $('<div>', {html: ajaxString});

$("b", $(virtualDiv)).css('background', '#ff0000');
$("body").html($("b", $(virtualDiv))[0]);

As per your comment you can use this to get all the html of virtual div:

$("body").html($(virtualDiv).html());
Jai
  • 74,255
  • 12
  • 74
  • 103
  • That's what I want! I have never hear before, like this. But how can I get back the whole string with a "replaced" element? For example: "qwe asd" and I need to get the whole string not just the "b" – Mate Jun 02 '16 at 10:10
  • @Mate then just use `.html()` as : `$("body").html($(virtualDiv).html());` ;) – Jai Jun 02 '16 at 10:14
0

here is a working fiddle of what you try to achieve

you should use filter

var newhtml = $('<b>asd</b><p>asd</p>');

newhtml.filter('b').each(function(){

$(this).css('font-size','50px')
$(this).css('color','blue')

});

newhtml.filter('p').each(function(){

$(this).css('font-size','20px')
$(this).css('color','red')

});

$('body').html(newhtml);

https://jsfiddle.net/c7a6spaj/

Cheers

erwan
  • 887
  • 8
  • 17