How to convert the p elements into the div to a array in javascript?

I saw using HTMLCollection could be a good way to do it but so far I haven’t been able to do it, help please.

<div id=”container”>
 <div class="divy"><p>Hello</p></div>
<div class="divy"><p>Hello</p></div>
<div class="divy"><p>Hello</p></div>
<div class="divy"><p>Hello</p></div>

What have you tried?

I don’t know what you want to do. but what I understood is below

let a=["<div><p> hellow </p></div>","<div><p> hellow </p></div>"]


You’re absolutely right, when you use (for example) something like

const divyElements = document.querySelectorAll("p.divy");

You will get, in the console, an HTMLCollection. That is a type of NodeList, which is a DOM construct containing HTML elements. It is referred to as Array-like, rather than a true array.

That said, under nearly all modern browsers, it will be handled as though it were an array. Older browsers wouldn’t allow for it, but with Chrome or Firefox, you can use divyElements anywhere you would use an array. You can map over them, filter them, reduce them, forEach them… They are, for all intents and purposes, an array. In modern browsers.

If you wanted to be “suspenders and belt”, making sure your bases were covered, you could convert them to an array explicitly. There are a number of ways to do that:

1 Like