Skip to content

Instantly share code, notes, and snippets.

@amitasaurus
Created April 30, 2024 05:12
Show Gist options
  • Save amitasaurus/26b2a01df0a1d832be729f51b50326fa to your computer and use it in GitHub Desktop.
Save amitasaurus/26b2a01df0a1d832be729f51b50326fa to your computer and use it in GitHub Desktop.
getElementsByClassName() is a method which exists on HTML Documents and Elements to return an HTMLCollection of descendant elements within the Document/Element which has the specified class name(s).
export default function getElementsByClassName(
element: Element,
classNames: string
): Array<Element> {
const elementsArr: Element[] = [];
function traverseNode(el: Element) {
if (el.hasChildNodes()) {
el.childNodes.forEach((node) => {
const nodeEl = node as Element;
if (nodeEl.nodeType === Node.ELEMENT_NODE) {
let attr: string | null = nodeEl.getAttribute('class');
if (!attr) return;
let classMap: Record<string, number> = {};
attr?.split(' ').map((e: string) => {
if (e.length > 0) classMap[e.trim()] = 1;
});
const classes = classNames.split(' ').filter((cls) => cls.length > 0);
const classMatch = classes.every((className) => {
return Boolean(classMap[className]);
});
if (classMatch) elementsArr.push(nodeEl);
traverseNode(nodeEl);
}
});
}
}
traverseNode(element);
return elementsArr;
}
// const doc = new DOMParser().parseFromString(
// `<div class="foo bar baz">
// <span class="bar baz">Span</span>
// <p class="fooz baz">Paragraph</p>
// <div class="foo bar"></div>
// </div>`,
// 'text/html'
// );
const doc = new DOMParser().parseFromString(
`<div class="foo bar foo baz">
<span class="bar baz bar">Span</span>
<p class="foo baz baz">Paragraph</p>
<div class="foo bar bar bar"></div>
</div>`,
'text/html'
);
console.log(getElementsByClassName(doc.body, ' foo foo bar '));
// console.log(getElementsByClassName(doc.body, 'foo bar'));
// console.log(getElementsByClassName(doc.body, 'foo'));
@amitasaurus
Copy link
Author

getElementsByClassName() is a method which exists on HTML Documents and Elements to return an HTMLCollection of descendant elements within the Document/Element which has the specified class name(s).

Let's implement our own Element.getElementsByClassName() that is similar but slightly different:

It is a pure function which takes in an element and a classNames string, a string containing one or more class names to match on, separated by whitespace.
Like Element.getElementsByClassName(), only descendants of the specified element are searched, not the element itself.
Return an array of Elements, instead of an HTMLCollection of Elements.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment