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
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.
CodePudding user response:
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: