Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Just about any <a href="http://en.wikipedia.org/wiki/List_of_JavaScript_libraries" rel="nofollow noreferrer">Javascript library</a> (<a href="http://prototypejs.org" rel="nofollow noreferrer">Prototype</a>, <a href="http://jquery.com" rel="nofollow noreferrer">jQuery</a>, <a href="http://code.google.com/closure/library" rel="nofollow noreferrer">Closure</a>, ...) will make this easier, but if you want to do it yourself:</p> <p>You're close, your Javascript should look something like this:</p> <pre><code>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 &amp;&amp; node.tagName == 'LI') { list.push(node.innerHTML); } } // `list` now contains the HTML of each LI element under the `ul#list` element } </code></pre> <p>Explanation:</p> <ul> <li>Before using <code>document.getElementById</code>, you need to be sure that the DOM is ready for you to do that. It's definitely ready at <code>onload</code> 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).</li> <li>The loop starts by getting the <code>ul#list</code> element's first child, then continues as long as there are further siblings.</li> <li>In the loop, we check that each node is an Element (<code>nodeType == 1</code>) and that its tag name is "LI".</li> <li>If it is, we retrieve its HTML and push it on the array.</li> </ul> <p>I've used <code>innerHTML</code> to retrieve the content of the LIs because it's widely supported. Alternately, you could use <code>innerText</code> on IE (and some others) and <code>textContent</code> on Firefox, but beware that they don't do <em>quite</em> the same thing (<code>textContent</code> on Firefox will include the contents of <code>script</code> tags, for instance, which probably isn't what you want).</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload