如何将列表项放入javascript数组中
我有一个包含一些 HTML 的变量。该 HTML 不在文档正文中 - 仅在变量中!由此,我想提取每个 li
的内容并将其放入一个数组中,以便我可以为每个列表项创建新的内容。
我可以做这样的事情吗?
var myList = "<ul><li>item 1</li><li>item 2</li><li>item 3</li></ul>";
myList.getElementByTagName('LI') = myLiContents;
感谢您的关注!
I have a variable which contains some HTML. This HTML is not on the document body - only in the variable! From this, I want to extract the contents of each li
and put it into an array, so that I can make something new with each list item.
Can I do something like this?
var myList = "<ul><li>item 1</li><li>item 2</li><li>item 3</li></ul>";
myList.getElementByTagName('LI') = myLiContents;
Thanks for looking!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以创建一个虚拟元素,并将该元素的
innerHTML
设置为您拥有的 HTML 字符串:但请注意,
getElementsByTagName
的结果不是一个数组,而是一个nodeList
,一个类似数组的对象。不过,您仍然可以通过nodeList
运行循环来创建真正的数组。You can create a dummy element and set the
innerHTML
of that element as the HTML string you have:Note however that the result of
getElementsByTagName
is not an array, but anodeList
, an array-like object. You can still run a loop through thenodeList
to create a real array though.您不能在字符串上使用
getElementByTagName
...只能在插入到文档中的 HTML 元素上使用。但对于您想要实现的目标,您实际上并不需要这样做。您可以使用正则表达式从字符串中提取所有:
这将生成一个如下所示的数组:
去除多余的
和
您可以在循环遍历每个项目时进行字符串替换:
You can't use
getElementByTagName
on a string... only on HTML elements inserted into the document. But for what you're trying to achieve, you don't really need to do that. You can use a regexp to extract all the<li>
s from your string:Which will produce an array like this:
To get rid of the extra
<li>
and</li>
you can do a string replace as you're looping through each item: