Mate Mate - 1 year ago 119
jQuery Question

How to add a new attribute for a HTML element before added to DOM with jQuery

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');

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

Thanks for the Help!

Jai Jai
Answer Source

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:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download