I’m trying to create an unordered list in javascript. My code reads:
$(div).append("<ul>")
for (i in usersLst){
$(div).append("<li>")
$(div).append(usersLst[i][1])
$(div).append("</li>")
}
$(div).append("</ul>")
Then the result is:
•
bob
•
alice
•
fred
However, if the code reads:
$(div).append("<ul>")
for (i in usersLst){
$(div).append("<li>"+usersLst[i][1]+"</li>")
}
$(div).append("</ul>")
Then the result is:
- bob
- alice
- fred
So with three separate appends it appears that a newline is being mysteriously inserted. What’s going on?
Assume this code:
Lets have a look at the resulting structure (Chrome 21):
What happend?
.appendtakes each argument and converts the strings to proper DOM elements. Thus the code is the same as doing:The two calls containing closing tags are ignored since they cannot be convert to valid HTML / DOM elements.
.append(and all other DOM manipulation methods) is working on DOM elements. It’s just jQuery’s way of calling.appendChild[MDN].HTML is just a specific format of representing structure. In there, each element is represented by a opening tag and an (optional) closing tag. The browser is parsing the HTML and creates the DOM in memory. The DOM (Document Object Model) is a well defined interface for interacting with hierarchical, structured data. Once you are working with the DOM, start and end tags don’t exist anymore (that’s HTML), only Nodes. I recommend to read about DOM on MDN.
jQuery allows you to pass HTML strings to
.appendbecause it is convient, but each string is immediately converted to corresponding DOM nodes and appended to other nodes. You cannot build an HTML string with multiple calls to.append.This is a corrected version of your code: