Alex Alex - 1 year ago 97
jQuery Question

JQuery, create element with dynamic class

I am trying to create elements with dynamic class value, so far unsuccessful. Here's code:

let sender = "alex";
let message = "testMsg";
let time = "15:30";
let msg = $('<span>')
.append($('<span>', {class : 'timestamp'}, {text: time}))
.append($('<p>', {class : sender}, {text: message}));

Results in the following:

<span id="timestamp"></span>

Which is confusing, because I read here that this more "elegant" way allows for variables to be used as dynamical properties. What am I missing here?


Solved: Turns out that I tried to give 3 paramethers to .append() function. Read bellow for solutions and explanation.

Answer Source

You were close, Here are small changes which I have done:

  1. Specify tag properly it should be <span> not </span>
  2. Use correct API, you can pass multiple arguments. $('<span />', {class: 'timestamp', text: time })
  3. Define all variables i.e. time was not defined.
  4. should not insert a <p> inside a <span>, Pointed out by @blex

let sender = "alex",
  message = "testMsg",
  time = '15:30';

let msg = $('<span>')
  .append($('<span>', {
    class: 'timestamp',
    text: time
  .append($('<p>', {
    class: sender,
    text: message

<script src=""></script>

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