FrontendArk

Master Frontend Interviews

  • Practice
  • Playground
  • Resource
Medium

Get Elements By ClassName

25mins

Implement a function getElementsByClassName(element, classNames) that finds descendant elements with the specified class names.

The function should:

  • Accept an Element as the root.
  • Accept a string of class names (separated by spaces) to match.
  • Only search descendants of the element, not the element itself.
  • Return an array of elements (not HTMLCollection).
  • Not use querySelectorAll.

Example

const doc = new DOMParser().parseFromString( `<div class="foo bar baz"> <span class="bar baz">Span</span> <p class="foo baz">Paragraph</p> <div class="foo bar"></div> </div>`, 'text/html' ); getElementsByClassName(doc.body, 'foo bar'); // [div.foo.bar.baz, div.foo.bar]

Code Editor

JavaScript Function

00:00
Loading...

Test Cases

No test results yet

Click "Run" to execute tests