1

I have an unordered list, each element of which I want to put in an array.

<div id='main'>
 <ul>
  <li>First</li>
  <li>Second</li>
 </ul>
</div>

I need to transfer it to JSON object like this:

"type": "list",
"data": ["* First", "* Second"]

For now, i have function which return all data from list in string:

let newObj = document.createElement("div");
newObj.innerHTML = document.getElementsByTagName('UL')[0].innerHTML;
[...newObj.querySelectorAll("li")].forEach(ele => ele.parentNode.replaceChild(document.createTextNode("* "+ele.textContent)),ele);
return newObj

2 Answers 2

8

You can select all of the li. Then map it getting textContent and adding * as prefix

const items = document.querySelectorAll('#main li');
const result = {
  type: 'list',
  data: Array.from(items).map(el => `* ${el.textContent}`),
}
console.log(result)
<div id="main">
  <ul>
    <li>First</li>
    <li>Second</li>
  </ul>
</div>

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

Comments

-1

You can use jquery:

let $li = $('#main').find('li') //returns a collection
let array = $.map($li, e => '* ' + e.textContent)

Converting to JSON:

let toJson = JSON.stringify(array)

1 Comment

OP does not mention jquery, and jquery does not bring any additional value over mark's answer

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.