When I use the code below, the generated html is placing the closing ul tag right behind the opening ul tag like so: <ul></ul><li>Food</li><li>Rent</li><li>Stuff</li>
How do I properly concatenate this, so the ul elements show correctly?
objTransDetails.innerHTML = "<ul>";
for (i = 0; i < transElements.length; i++) {
objTransDetails.innerHTML += "<li>" + transElements[i].firstChild.data开发者_JS百科 + "</li>";
}
objTransDetails.innerHTML += "</ul>";
First, don't forget var
!!!
for (var i = 0; i < transElements.length; i++)
Now, I think the main problem is that you're building up the HTML right in the "innerHTML" value, which really won't work out very well; it's not just a string, it's like a conduit straight to the browser's brain. Build up the replacement HTML in a temporary variable, and then set it all at once.
The reason you see the effect that you do is that when you start the process and set the "innerHTML" to nothing but the string "<ul>", the browser obliges by adding the missing close tag (effectively). When you next access "innerHTML", therefore, what you get is "<ul></ul>" because that's the corrected form of what you put there last.
Try inserting the entire HTML block at once:
var contents = "<ul>";
for (var i = 0; i < transElements.length; i++) {
contents += "<li>" + transElements[i].firstChild.data + "</li>";
}
contents += "</ul>";
objTransDetails.innerHTML = contents;
Edit: Also as @Pointy points out, make sure to use var
Don't use innerHTML with literal HTML tag strings. There's many unsafe things that can happen, but that's the subject of another thread. You're dealing with objects, so don't treat them like strings.
var ul = document.createElement('ul');
objTransDetails.appendChild(ul);
var li;
for (var i = 0; i < transElements.length; i++) {
li = document.createElement('li');
li.innerHTML = transElements[i].firstChild.data;
ul.appendChild(li);
}
精彩评论