How to make list-items into javascript array
I have a variable which contains some HTML. This HTML is not on the document body - only in the variable! From t开发者_高级运维his, 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!
You can create a dummy element and set the innerHTML
of that element as the HTML string you have:
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. You can still run a loop through the nodeList
to create a real array though.
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:
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[i].replace(/<\/?li>/gi, "");
精彩评论