2019-06-13
Return the DOM elements via a CSS selector
stackoverflow
Question

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`

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);

Note that the inverse traverse order matters

The output

enter image description here

Hope it helps.

Protip: use const and let for vars now. Actually, "let is the new var".

Return the DOM elements via a CSS selector
See more ...
Related Questions
Related Documents