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

Asked

Viewed 552 times

1

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

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

This way up I will have a div with the red color text ok, now is the following.

I’m getting a STRING which contains all the tag code so:

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

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

My question is whether there is how I saw jQuery make the modifications or I will have to do everything in hand by moving the whole string directly?

2 answers

1


Use jQuery.parseHTML() to turn your string into a gift object, then you can insert that object into 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>

  • Thanks, it looks really good this way.

0

I managed to make a beautiful 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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.