如何将无序列表项放入数组中 [英] How do I put unordered list items into an array

查看:63
本文介绍了如何将无序列表项放入数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码是......

My code is...

如何使用原生javascript将每个列表项中的文本转换为数组?

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>

非常感谢。

推荐答案

除非你想要每个< li> 之间的文本节点,否则使用 childNodes getElementsByTagName('li')有什么问题?

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;
}

这篇关于如何将无序列表项放入数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆