Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert all children of a div to an array

I have a div and I want to convert all of its children to an array.
So the expected output from this should be:

numbers = ['<div>Lorem ipsum<h1>Dolores</h1><h2>Test</h2>Lorem final<div>']

HTML

<div>
 Lorem ipsum
 <h1>Dolores</h1> 
 <h2>Test</h2>
 Lorem final
<div>

JS

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

convertToArray() {
    let numbers = Document.querySelector(':scope > div');
    // let numbers = Array.prototype.slice.call(nodes);
    // let numbers = Array.prototype.slice.call(nodes);  
    // console.log(Array.from(numbers));
    console.log(numbers);
}

The logged result is always empty.

I tried using a couple of ES5 & ES6 answers found on stackoverflow, but none of them work when applied to all the children of an element.

>Solution :

One approach is as follows, with explanatory comments in the code:

// declaring the function as an Arrow function, passing in
// a CSS selector:
const convertToArray = (selector) => {
  // using document.querySelectorAll() to find all instances of
  // the elements matching the selector, with an Array literal
  // and spread syntax to convert the NodeList into an Array
  // of nodes:
  let sources = [...document.querySelectorAll(selector)];
  // iterating over the Array of nodes, with Array.prototype.map()
  // to return a new Array based on the first:
  return sources.map(
    // an Arrow function passing the current node ('el') into
    // the function, retrieving its Element.outerHTML property
    // and returning that as the new Array-element:
    (el) => el.outerHTML
  );
}

console.log(convertToArray('div'));
<div>
  Lorem ipsum
  <h1>Dolores</h1>
  <h2>Test</h2>
  Lorem final
</div>

References:

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading