Almost any Javascript library ( Prototype , jQuery , Closure , ...) will make it 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 must be sure that the DOM is ready for this. It is definitely ready for onload
time, and there are various mechanisms for running your code a little earlier than you like (including if you put an end to the script at the end). - The loop begins by receiving the element of the
ul#list
element as the first child, and then continues until there are other siblings. - In the loop, we verify that each node is an Element (
nodeType == 1
) and that its tag name is "LI". - If so, we get its HTML and click on the array.
I used innerHTML
to retrieve LI content because it is widely supported. Alternatively, you can use innerText
for IE (and some others) and textContent
for Firefox, but be careful that they donโt do the same ( textContent
in Firefox will include the contents of script
tags for example, which is probably not what you want to).
source share