jquery create multiple elements and append

Hello i’m working on a socket io chat and i’m trying to append the users username and message but i’m trying to put the username inside a strong tag.

I have tried

$('<div>').text('<strong>' + username + ': </strong>' + msg).addClass('alert').appendTo('#chat');

And also tried this but could not workout how to put the message.

$('<div>').text(username).addClass('alert').appendTo($('<strong>').appendTo($('#chat')));

I need to use text and not html because xss attack vulnerability.

const username = 'My username';
const msg = 'This is a test message';

// first try
$('<div>').text('<strong>' + username + ': </strong>' + msg).addClass('alert').appendTo('#chat');

// second try
$('<div>').text(username).addClass('alert').appendTo($('<strong>').appendTo($('#chat')));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="chat"></div>

Answer

You don’t have to put everything in a single chained line. I’d first create and append the <div>, then create a <strong> tag with the text and prepend it to the div:

const username = 'My username';
const msg = 'This is a test message';

const div = $('<div>')
  .addClass('alert')
  .text(msg)
  .appendTo('#chat');
$('<strong />')
  .text(username)
  .prependTo(div);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="chat"></div>

It’s possible with only a single chain, but I don’t like it that much:

const username = 'My username';
const msg = 'This is a test message';

const div = $('<div>')
  .addClass('alert')
  .html('<strong />')
  .append(msg)
  .appendTo('#chat')
  .find('strong')
  .text(username);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="chat"></div>

Leave a Reply

Your email address will not be published. Required fields are marked *