Skip to content Skip to sidebar Skip to footer

Using .append() With Lists Places Text On A Newline

I'm trying to create an unordered list in javascript. My code reads: $(div).append('
    ') for (i in usersLst){ $(div).append('
  • ') $(div).append(usersLst[i]

Solution 1:

Assume this code:

$('div')
    .append("<ul>")
    .append("<li>");
    .append('foo');
    .append("</li>")
    .append("</ul>")​​​

Lets have a look at the resulting structure (Chrome 21):

<div>
    <ul></ul>
    <li></li>
    foo
</div>

What happend? .append takes each argument and converts the strings to proper DOM elements. Thus the code is the same as doing:

$('div')
   .append(document.createElement('ul'))
   .append(document.createElement('li'));
   .append(document.createTextNode('foo'));

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.

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 .append because 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:

// jQuery parses the HTML string and creates a UL elementvar$ul = $('<ul />');
// equivalent to// var $ul = document.createElement('ul'); <- NOTE: not HTML, it's a node namefor (var i in usersLst) {
    // jQuery parses the HTML, creates a LI element and appends it to the list$ul.append('<li>' + usersLst[i][1] + '</li>');
    // equivalent to// var li = document.createElement('li');// li.appendChild(document.createTextNode(usersLst[i][1]));// $ul.appendChild(li);
}

// append the populated UL element to an existing node:
$(div).append($ul);
// equivalent to// existingElement.appendChild($ul);

Solution 2:

They are both incorrect. You should create the entire string first, then append it to the DIV:

var ul = '<ul>';
for (i in usersLst){
    ul+='<li>' + usersLst[i][1] + '</li>';
}
ul+='</ul>';

$(div).append(ul)

Post a Comment for "Using .append() With Lists Places Text On A Newline"