jay jay - 1 year ago 71
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>');
var plotDiv2 = $('#myDiv3');

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

Answer Source

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>';

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+')'


var plotDiv2 = $('#myDiv3')
.myDiv {
  position: relative;
  width: 50px;
  height: 50px;
<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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download