+0.1Coin iconReturn 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`

Coin iconoffer bounty
add comment

1 Answer

1

Maybe you want to do a for of and clone the element for attribute removal. Like this…

const selectors = document.getElementsByClassName("Class3");
const arr = [];
for (let selector of selectors) {
  const element = selector.cloneNode();
  for (let i = element.attributes.length - 1; i >= 0; i--) {
    element.removeAttribute(element.attributes[i].name);
  }
  arr.push(element);
}
console.log(selectors, arr);
add comment

Your Answer