Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I put unordered list items into an array

Tags:

javascript

My code is...

How do I get the text in each list item into an array using native javascript?

<ul id="list">
    <li>List Item 1</li>
    <li>List Item 2</li>
    <li>List Item 3</li>
    <li>List Item 4</li>
</ul>

<script type="text/javascript">
var list = document.getElementById('list').childNodes.TextNode;
for(var i=0;i < list.length; i++) {
    var arrValue = list[i];
    alert(arrValue);
}
</script>

Many thanks.


2 Answers

Unless you want the text-nodes between each <li> it's not a good idea to use childNodes. What's wrong with getElementsByTagName('li')?

var listItems = document.getElementById('list').getElementsByTagName('li'),

    myArray = map(listItems, getText);

function map(arrayLike, fn) {
    var ret = [], i = -1, len = arrayLike.length;
    while (++i < len) ret[i] = fn(arrayLike[i]);
    return ret;
}

function getText(node) {
    if (node.nodeType === 3) return node.data;
    var txt = '';
    if (node = node.firstChild) do {
        txt += getText(node);
    } while (node = node.nextSibling);
    return txt;
}
like image 139
James Avatar answered Oct 30 '25 01:10

James


Try this:

var list = document.getElementById('list').childNodes;
var theArray = [];
for(var i=0;i < list.length; i++) {
    var arrValue = list[i].innerHTML;
    alert(arrValue);
    theArray.push(arrValue);
}
like image 29
nickf Avatar answered Oct 30 '25 03:10

nickf