Concatenate elements

1

I'm having trouble concatenating the elements below.

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

However, I can not enter the information.

var valorID='meuID';
var valorPosicao=20;
$("body").prepend('<div id='+valorID+'style=position:absolute;left:'+valorPosicao+'px;'+'></div>');
    
asked by anonymous 05.07.2018 / 22:21

3 answers

3

Every div attribute value should come between "". In case of using js it should be:

...

id="'+valorID+'"

...
  • Here is your refactored code:

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>
    
05.07.2018 / 23:01
2

You do not need to concatenate the string, you can use jQuery's element-manipulation 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
    
05.07.2018 / 22:26
2

Use jQuery itself. That's enough:

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

Here is an example to run. In the console it 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>
    
05.07.2018 / 23:15