1

Suppose I have an unordered list and I wanted to push the html of that list into an array, such that the output looked like the following:

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

How might this be achieved?

1 Answer 1

6

If you want to get an array of Element objects then just $('li').get() will suffice.

If you want each li element as a string of HTML then you can use map() along with outerHTML, like this:

var arr = $('li').map(function() {
  return this.outerHTML;
}).get();
console.log(arr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li>item 1</li>
  <li>item 2</li>
  <li>item 3</li>
</ul>

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

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.