0

I am new to javascript and jquery.

I am trying to add html from a javascript function.

To place the contents of y at a specific location I am adding a div tag "Contacts" and trying to append elements to it.

But the contents of "y" are not being displayed.

My code:

componentHtml += "<div id = Contacts>";
var y = [ 1, 2, 3 ];
$("#Contacts").append(y);
componentHtml += "</div>
GG.
  • 21,083
  • 14
  • 84
  • 130
user2990315
  • 271
  • 1
  • 5
  • 11
  • 1
    1) you wrongly assign id to element. 2) Div that you create is not in DOM tree yet. So you need to add this div to DOM tree and after that you will be able to use $('#..."); Although you can create virtual div. – Yuriy Yakym Apr 17 '16 at 15:37
  • change `componentHtml += "
    ";` to `componentHtml += "
    "; `
    – Tirth Patel Apr 17 '16 at 15:38
  • Unless you `componentHtml` is added to DOM there's no `$("#Contacts")` element available. – u_mulder Apr 17 '16 at 15:39

2 Answers2

3

There are several problems with your code.

  1. "<div id = Contacts>" should be '<div id="Contacts">'.
  2. You try to $("#Contacts").append(y); but your div is not in the DOM yet.
  3. You try to append an array of numbers into a div. .append doesn't work like that.

The code below solves those problems:

var contacts = $('<div>', { id: 'Contacts' });

var y = [ 1, 2, 3 ];

var content = y.join();

contacts.html(content);

$('body').append(contacts);

Have a look at .join([separator]) to see different examples of output.

GG.
  • 21,083
  • 14
  • 84
  • 130
2

componentHtml is just a string at the moment you exec $("#Contacts").append(y);. And as it is just a string - there's no #Contacts element in your DOM. So $("#Contacts") finds nothing.

Simplest solution is use join, for example:

componentHtml += "<div id = Contacts>";
var y = [ 1, 2, 3 ];
componentHtml += y.join("<br />");   // or any other delimiter
componentHtml += "</div>
u_mulder
  • 54,101
  • 5
  • 48
  • 64