jay jay - 3 months ago 8
HTML Question

Trying to access appended element in JQUERY

var count=3;
socket.once('temp', function(temp){
for (var i= 1; i < temp.length; i++) {
$('#graphs').append('<div class= "myDiv2"' id="myDiv' + count + '" position:"relative;" style="width: 85%; height: 550px;">hi</div>');
count++;
};
});
var plotDiv2 = $('#myDiv3');
console.log(plotDiv2);


When i try to print this appended div out, nothing prints out? How do I correctly access the appended div?

Answer

It seems your quotes are mismatched. Notice the syntax color-coding in your post.
As such, the code throws a syntax error:

Uncaught SyntaxError: Unexpected identifier

Here's a valid version:

var count = 3,
    html = '<div class= "myDiv2" id="myDiv' + count + '" position:"relative;" style="width:50px; height:50px;">hi</div>';

jQuery('body').append(html);
div {
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


However, to simplify things, I suggest using jQuery to create the new element, rather than directly concatenating an HTML string.

var $graphs=jQuery('#graphs');

for (var count = 3; count < 5; count++) {

  jQuery('<div>', {
    'class': 'myDiv',
    'id': 'myDiv' + count,
    'text': 'hi ('+count+')'
  }).appendTo($graphs);

};

var plotDiv2 = $('#myDiv3')
console.log(plotDiv2);
.myDiv {
  position: relative;
  width: 50px;
  height: 50px;
  background-color:red;
  margin:1em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="graphs"></div>

See this answer for more reference.

Comments