OrElse
OrElse

Reputation: 9959

How can i render valid html with JQuery?

i tried to create valid html by using the append function but the desired output is not valid. Is there any other function in JQuery that could i use?

  $('#d').empty();
  $('#d').append('<ul class="ch">');
  for (i = 0; i < messages.length; i++) {

      $('#d').append('<li class="in">');
      $('#d').append('<img class="avatar">');
      $('#d').append('  <div class="message">');
      $('#d').append('      <span class="arrow"></span>');
      $('#d').append('      <a href="#" class="name">'+ userName +'</a>');
      $('#d').append('      <span class="datetime">at 11/11/1111</span>');
      $('#d').append('      <span class="body">' + message + '</span>');
      $('#d').append('  </div>');
      $('#d').append('</li>');
  }
  $('#d').append('</ul>');

Upvotes: 1

Views: 50

Answers (2)

Vasiliy vvscode Vanchuk
Vasiliy vvscode Vanchuk

Reputation: 7169

Use

$('#d').html('Your code here')

It's more easier.

Also you can store such picks of code at template blocks - and use replace functions ( or better - take a look to js tamplates engines - like handlebars, underscore etc ).

Also in your case you can just append whole the code in one step

$('#d').append('<li class="in"><img class="avatar"><div class="message"><span class="arrow"></span>
<a href="#" class="name">{USER}</a><span class="datetime">at 11/11/1111</span> <span class="body">{MSG}</span> </div> </li>'.raplace('{USER}', username).replace('{MSG}', message) )

(If you'll store you html code at template block you've got an ability fo format if pretty )

For your case it can look's like http://jsbin.com/zihiticeva/1/edit?html,js,output

Upvotes: 4

mfarouk
mfarouk

Reputation: 654

the problem with append is that it should append full html element

this will not work as expected ( i tested this on jsfiddle and it added two li elements)

$('#d').append('<li class="in">');
$('#d').append('</li>');

this should work

$('#d').append('<li class="in"></li>');

Upvotes: 1

Related Questions