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.
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;
}
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With