Concatenate elements

Asked

Viewed 992 times

1

I’m having trouble concatenating the elements below.

I have the variable valorID which is used as id, in div, and I’m trying to insert it into id and valorPosicao for the attribute left, of inline css.

However, I am unable to enter the information.

var valorID='meuID';
var valorPosicao=20;
$("body").prepend('<div id='+valorID+'style=position:absolute;left:'+valorPosicao+'px;'+'></div>');
  • There’s an extra '+' there at the end

3 answers

3


Every attribute value of div, must come between "". In the case of using js must be:

...

id="'+valorID+'"

...
  • Follows below your code refactored:

var valorID='meuID';
var valorPosicao=20;
$("body").prepend('<div id="'+valorID+'style=position:absolute;left:'+valorPosicao+'px;'+'">teste</div>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body></body>

  • 2

    The browser adds the automatic quotes. But I go with vc, I like to do it right. : D

  • kkkkkkkkkkkkk

2

You do not need to concatenate into the string, you can use jQuery’s element handling methods:

var valorID = 'meuID';    
var valorPosicao = 20;

var minhaDiv = $('<div>'); //Criando a Div 
minhaDiv.attr('id', valorID); //Adicionando Id
minhaDiv.css('position', 'absolute') //Adicionando Css
    .css('left', valorPosicao);

$("body").prepend(minhaDiv); //Prepend na variavel

2

Use jQuery itself. So just:

$('<div/>', {id: valorID}).css({'position': 'absolute', 'left': valorPosicao + 'px'}).prependTo('body');

Follow example to run. In the console appears the div inserted in the DOM.

var valorID='meuID';
var valorPosicao=20;

var div = $('<div/>', {id: valorID}).css(
{
'position': 'absolute', 
'left': valorPosicao + 'px'
}
)
.prependTo('body');

console.log(div[0]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
</body>
</html>

Browser other questions tagged

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