+0.1Return the DOM elements via a CSS selector

Ask a question
1

Say I have these lines of HTML:

<div id="ID1" class="Class1 Class3"></div>
<p id="ID2" class="Class2 Class3"></p>

I want to be able to return the HTML elements in an array given a CSS selector or TagName, this is what I have so far:

const selectors = document.getElementsByClassName("Class3");

let arr = [];
while (selectors) {
  arr.push(selectors);
  selectors = selectors.parentNode;
}

console.log(arr);
<div id="ID1" class="Class1 Class3"></div>
<p id="ID2" class="Class2 Class3"></p>

This code works and returns the HTML elements, but how do I alter the code so it just returns the HTML elements (div and p), rather than the HTML elements as well as CSS selectors - if possible?

So that the output is:[div, p]

EDIT I can’t use document.querySelector/document.querySelectorAll or any libraries`

offer bounty
add comment

0 Answer

Your Answer