jQuery - create a jQuery element (create a tag) from a string

1

I have made to create an element (a tag) the following code:

var b = $('<div>').css('color','red');

In this way above I will have a div with the text red color ok, now it is the following.

I'm getting a STRING that contains all the tag code like this:

var a = "<div style=\"text-overflow: ellipsis; overflow: hidden; padding-bottom: 2px; text-align: center; margin-top: 4px;\">47782</div>";
$(a).css('color','red'); //TENTATIVA DE ALTERAR A COR, MAS NÃO DA ERRO NEM FUNCIONA

But this is not changing, I can not create this tag as in the first code snippet, because the content of this string is received dynamically in my script.

My question is whether I have seen jQuery make the modifications or will I have to do everything in the hand by directly moving the entire string?

    
asked by anonymous 14.08.2015 / 20:38

2 answers

1

Use jQuery.parseHTML () to transform your string into an object of the gift, then you can insert that object on the page.

var a = "<div style=\"text-overflow: ellipsis; overflow: hidden; padding-bottom: 2px; text-align: center; margin-top: 4px;\">47782</div>";
var meuHtml = $.parseHTML(a);
$(meuHtml).css('color','red');
$("body").append(meuHtml);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
  
</body>
    
14.08.2015 / 20:55
0

I managed to make a beautiful one of a gambiarra

var a = "<div style=\"text-overflow: ellipsis; overflow: hidden; padding-bottom: 2px; text-align: center; margin-top: 4px;\">47782</div>";
    
$('body').append(
  $(a).wrap('<div>').css('color','red').parent().html()  
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
14.08.2015 / 21:01