hughesdan
hughesdan

Reputation: 2851

Using jQuery .append() to insert a div into a table cell

I'm attempting to create divs in an table using jQuery. The table represents a calendar with each <td> having an ID that is equal to the ISO formatted date string. In the code below I'm having a problem with the append line. It is not adding anything to the DOM. I've checked the tdID values against the IDs for the cells and they do indeed match. So I'm fairly certain that is not the issue. Can someone spot where I may have gone wrong?

if (loopDate.between(past, future)) {
   var tdID = loopDate.toISOString();
   $("#" + tdID).append("<div class=&quot Event &quot>" 
                   + data.events[i].Est + "</div>");
}

Edit --- here's a sample of my html. The "d" is a character I added to the beginning of the ID to address the issue noted by @Matt Stauffer.

<td id="d2012-02-01T05:00:00.000Z">1</td>

Upvotes: 1

Views: 4006

Answers (6)

Kypros
Kypros

Reputation: 2986

Now that i see your id, although it is valid as a naming convention for the id attribute as for HTML where:

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

the problem in your case is in the use of dots (.) and colons(.) as when you are using the jquery selector, the dot(.) is interpreted as searching for a class or subclass and the colon(:) as searching for :first, :last etc

To solve your problem you could try replacing those characters with undescores(_) or hyphens(-) which should be fine.

You can check this over here at this jsFiddle

Upvotes: 2

Yanuar Lutfi
Yanuar Lutfi

Reputation: 153

if (loopDate.between(past, future)) {
  var tdID = loopDate.toISOString();
  var tdDiv = document.createElement('div');
  tdDiv.addClass("Event");
  tdDiv.html(data.events[i].Est);
  $("#" + tdID).html(tdDiv);
}

Upvotes: 0

Matt Stauffer
Matt Stauffer

Reputation: 2742

ID's can't start with a number, and I believe an ISO-formatted date would start with a number, so you're using invalid IDs.

Also, as others have mentioned,

"<div class=&quot Event &quot>"

Should be

"<div class=\"Event\">"

Upvotes: 2

Greg Kramida
Greg Kramida

Reputation: 4244

Alternatively, you can use

var div = document.createElement('div');
$(div).addClass("Event");
$(div).append(data.events[i].Est);
$("#" + tdID).append(div);

-- much cleaner type of coding...

Upvotes: 1

leemeichin
leemeichin

Reputation: 3379

You're using escaped HTML entities in the append function, so you need to change:

"<div class=&quot Event &quot>"

to:

"<div class='event'>"...
// or
"<div class=\"event\">"...

Upvotes: 1

SLaks
SLaks

Reputation: 887479

Don't use &quot; you need a lexical " there.
You need to Javascript-escape the string literal by writing \".

Upvotes: 3

Related Questions