简体   繁体   中英

Javascript appending; What is considered best practice?

Can anyone explain what is considered the best practice in appending in javascript?

var element = document.createElement('p');
element.innerHTML = 'This is appended' ;
var div = document.getElementById('div');
div.appendChild(element);

or

var div = document.getElementById('div');
div.innerHTML = '<p>This is appended</p>';

I see a lot of people doing it like this in jQuery:

$('#div').append('<p>This is appended</p>');

But i've always done it like this:

var element = document.createElement('p');
element.innerHTML = 'This is appended' ;
$('#div').append(element);

Thank you in advance

if you're using jQuery, absolutely nothing wrong with:

$('#div').append('<p>This is appended</p>');

Its less code and less steps.

IMO, when you're working with a DOM, treat it like a DOM instead of a string.

In other words, don't use markup to create elements or text nodes. Use DOM creation methods.

document.getElementById('div')
        .appendChild(document.createElement('p'))
        .appendChild(document.createTextNode('This is appended'));

Microsoft's .innerHTML invention can be tempting, and perhaps useful in a pinch, but I usually avoid it.

You can reduce the verbosity of the methods above with helpers.

I typically build an element using jQuery.

var paragraph = $("<p />", {
  className : "someClass",
  text : "this is appended"
})


div.append(paragraph)

I believe that this approach is preferred to directly injecting HTML because it's less intrusive on the DOM.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM