0

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!

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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, "");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.