Reputation: 317
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`
Upvotes: 0
Views: 403
Reputation: 2610
You can loop through the HTMLCollection that is returned by document.getElementsByClassName
using a simple for
loop.
Then using the index of each element then you can easily access the element.
You can either use nodeName
or localName
property of the element object to get their tags.
var s = document.getElementsByClassName("Class3");
let arr = [];
for(let i = 0; i <= s.length-1; i++){
arr.push(s[i].localName)
}
console.log(arr)
<div id="ID2" class="Class1 Class3"></div>
<p id="ID2" class="Class2 Class3"></p>
Upvotes: 1
Reputation: 532
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
Hope it helps.
Protip: use const
and let
for vars now. Actually, "let is the new var".
Upvotes: 1
Reputation: 1097
Use this JavaScript code
var s = document.querySelectorAll(".Class3");
var arr = [];
s.forEach((e, key) => {
arr.push(e.nodeName)
})
console.log(arr);
Upvotes: 0