Just about any Javascript library (Prototype, jQuery, Closure, ...) will make this easier, but if you want to do it yourself:
You're close, your Javascript should look something like this:
window.onload = onPageLoad; // Or any of several other similar mechanisms
// (you could just run it at the bottom of the page)
function onPageLoad() {
var node, list, arrValue;
list = [];
for (node = document.getElementById('list').firstChild;
node;
node = node.nextSibling) {
if (node.nodeType == 1 && node.tagName == 'LI') {
list.push(node.innerHTML);
}
}
// `list` now contains the HTML of each LI element under the `ul#list` element
}
Explanation:
- Before using
document.getElementById
, you need to be sure that the DOM is ready for you to do that. It's definitely ready at onload
time, and there are various mechanisms for triggering your code a bit earlier than that if you like (including putting the script right at the end).
- The loop starts by getting the
ul#list
element's first child, then continues as long as there are further siblings.
- In the loop, we check that each node is an Element (
nodeType == 1
) and that its tag name is "LI".
- If it is, we retrieve its HTML and push it on the array.
I've used innerHTML
to retrieve the content of the LIs because it's widely supported. Alternately, you could use innerText
on IE (and some others) and textContent
on Firefox, but beware that they don't do quite the same thing (textContent
on Firefox will include the contents of script
tags, for instance, which probably isn't what you want).