-1
    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?

jay
  • 85
  • 15
  • Your comment does not make sense to me. – jay Aug 09 '16 at 17:48
  • To start with... the ID of your appended div isn't `#myDiv3`, it's `#myDiv`. And your single and double quotes are completely messed up, not sure if it's a typo from your post or if that's really what your code looks like. Also, what does the markup actually say when you right click -> inspect in the browser? – Bek Aug 09 '16 at 17:56

1 Answers1

1

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.

I also suggest including your CSS definitions as an external style sheet rather than as inline styles directly in your HTML. See Inline tags vs. inline css properties for more reference.

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.prop('id'));
.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 another example.

Community
  • 1
  • 1
showdev
  • 28,454
  • 37
  • 55
  • 73