These two patterns yield different results, but conceptually I would expect them to be the same. The first just updates an existing <div> while the second appends <div>s sequentially. I anticipated that both would result with this second pattern. So I am curious about the differences in how these two patterns access the DOM to give the results they do.
Pattern 1
$(document).ready( function () {
var list = [
'My','name','is','Jonas'
];
$(list).each( function (key) {
$("body").append("<div>").text(list[key]);
});
});
Pattern 2
$(document).ready( function () {
var list = [
'My','name','is','Jonas'
];
$(list).each( function (key) {
$("<div />").text(list[key]).appendTo("body")
});
});
The difference is that
Pattern1 Add
divintobodyand then changebodytext.Pattern2 Create
divchange it’stextand then append tobodyWhy it happens ?
Because the first pattern’s selector is
body, so when you usetextit changesbodytext.How to fix ?