Ifch0o1
Ifch0o1

Reputation: 924

Differences between creating and writing html elements

I wanna know what is different between:

// Way 1
var html = '<div id="4" class="selected">
               <span id="span2">Content</span>
            </div>';


// Way 2 
var div = $('<div>').attr('id', 4).addClass('selected');
var span = $('<span>').attr('id', 'span2').text('Content');
div.append(span);
var html = div;

Way 1 is simple.

Way 2 looks good in this case, but when nested elements are more, may be difficult to write and read.

Is there anything special in Way 2 ?

Upvotes: 0

Views: 72

Answers (2)

Manish Jangir
Manish Jangir

Reputation: 5437

Way2 is for dynamic purpose only.

Upvotes: 0

henry4343
henry4343

Reputation: 3921

In Way2 you can edit each object easily. Like add text, delete tag or attribute. But in Way1 when nested elements are more, you cant find each area you want easily , and if you want to edit html, you will spend more time to look for your tag which you want to edit. So I think Way2 is better than Way1 when nested elements are more

Upvotes: 1

Related Questions