简体   繁体   English

如何将列表项放入javascript数组中

[英]How to make list-items into javascript array

I have a variable which contains some HTML. 我有一个包含一些HTML的变量。 This HTML is not on the document body - only in the variable! 此HTML不在文档正文中 - 仅在变量中! 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. 由此,我想提取每个li的内容并将其放入一个数组中,以便可以对每个列表项进行一些新的处理。

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! 谢谢你的期待!

You can create a dummy element and set the innerHTML of that element as the HTML string you have: 您可以创建一个虚拟元素,并将该元素的innerHTML设置为您拥有的HTML字符串:

var myList = "<ul><li>item 1</li><li>item 2</li><li>item 3</li></ul>",
    dummy = document.createElement('div');

dummy.innerHTML = myList;
console.log(dummy.getElementsByTagName('li'));

Note however that the result of getElementsByTagName is not an array, but a nodeList , an array-like object. 但是请注意, getElementsByTagName的结果不是数组,而是一个类似于数组的对象nodeList You can still run a loop through the nodeList to create a real array though. 您仍然可以通过nodeList运行循环来创建一个真实的数组。

You can't use getElementByTagName on a string... only on HTML elements inserted into the document. 您不能在字符串上使用getElementByTagName ...仅对插入到文档中的HTML元素使用。 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: 您可以使用正则表达式从字符串中提取所有<li>

var li = myList.match(/<li>.*?<\/li>/gi);

Which will produce an array like this: 这将产生这样的数组:

["<li>item 1</li>", "<li>item 2</li>", "<li>item 3</li>"]

To get rid of the extra <li> and </li> you can do a string replace as you're looping through each item: 要摆脱多余的<li></li> ,可以在遍历每个项目时进行字符串替换:

li[i].replace(/<\/?li>/gi, "");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM