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
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
Share Improve this question asked Jun 8, 2012 at 15:49 TheadamltTheadamlt 2752 gold badges5 silver badges18 bronze badges 3- All those solutions are good. If I'm using jQuery, My approach would be to take #3 as I like to keep my code short and I dislike #4 as it mixes vanilla javascript with jQuery, but all in all, any of those solutions can be used. – nebulousGirl Commented Jun 8, 2012 at 15:52
-
1
don't use
.innerHTML
if you are using jQuery. Anything that possibly removes elements must go through jQuery so that it won't leak memory. – Esailija Commented Jun 8, 2012 at 16:05 - @Esailija is absolutely right. For that matter, don't use other DOM manipulation libraries alongside jQuery, as the same leaks can occur. – user1106925 Commented Jun 8, 2012 at 16:13
3 Answers
Reset to default 5if 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.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745099141a4611166.html
评论列表(0条)