Alex Alex - 3 months ago 8
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>
<span id="timestamp"></span>
<p></p>
</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?

Thanks

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

Answer

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
  }));

$('div').append(msg)
.alex{color:green}
.timestamp{color:red}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>

Comments