pewpewlasers
pewpewlasers

Reputation: 3215

jQuery append text formatting

This question is not related to coding issues but how we write our codes. For example take the append function. When we use jQuery append to insert long divs, it is easy to lose track of it's correctness. Example:

$('#someDiv').append('<div><span><div> .............. hundreds of div here ..... </div></span></div>');

Is it possible to convert this to a readable format, for example using multi-lines. I tried

$('#someDiv').append('<div>'+
+'<span>'+
+'<div> ...... and you get the point')

This doesn't seem to work. This question may be easy for some but it is not so obvious for me. Also although I minify js files at the end, it would be nice not to lose track of the elements while writing the code.

Upvotes: 2

Views: 4871

Answers (3)

Adil Shaikh
Adil Shaikh

Reputation: 44740

You can do it this way -

$('#someDiv').append($('<div>').append($('<span>'))
                               .append($('<div>'))
                               .append($('<div>'))
                               .append($('<div>'))
                               .append($('<div>'))
)

You can also add css styles, add class, change html while appending these html elements (wrapped in jQuery object)

$('<div>').css('color','red')
$('<div>').addClass('someClass')
$('<div>').html("and you get the point")

Upvotes: 4

Martin
Martin

Reputation: 621

My solution would be to create all these elements

div1 = $(document.createElement('div'));
div1.attr(..);
div1.css(..);


container.append(..)

This means a lot of code but you can outsource it, can easily change attributes and its good readable...

Upvotes: 0

Index
Index

Reputation: 2381

If you have to add the HTML inline style I would suggest the following format.

var html =
'<div class="somediv">\
  <div class="otherdiv">\
    .
    ..
    ...
  </div>\
</div>';

$('#somediv').append(html);

Upvotes: 5

Related Questions