0
Hours
0
Minutes
0
Seconds
You need Login/Signup to run/submit the code.

How to implement getElementsByClassName? | Frontend Problem Solving | JavaScript Interview Question

@Devtools Tech
296

In this question, the candidate needs to build a function called getElementsByClassName that mimics the behaviour of the method with the same name provided by the DOM interface.

Description

The getElementsByClassName method of Document interface returns an array-like object of all child elements which have all of the given class name(s).

When called on the document object, the complete document is searched, including the root node. You may also call getElementsByClassName() on any element; it will return only elements which are descendants of the specified root element with the given class name(s).

Read more about getElementsByClassName here.

Syntax

getElementsByClassName(names)

Arguments

  • names: A string representing the class name(s) to match; multiple class names are separated by whitespace.

Return value

A live HTMLCollection of found elements.

Examples

  • Get all elements that have a class of 'test':
getElementsByClassName("test");
  • Get all elements that have both the 'red' and 'test' classes:
getElementsByClassName("red test");
  • Get the first element with a class of 'test', or undefined if there is no matching element:
getElementsByClassName("test")[0];

Submission

Start the timer, complete your solution, test your solution against the test cases provided by the platform, and submit it. Ideally, you should finish this question within 60 mins.

Share your solution with us on twitter or linkedin.

Loading IDE...