DEV Community

loading...

Writing a polyfill for getElementsByClassName()

vishal0203 profile image Vishal Sharma ・2 min read

Since the start of this new year I've started posting code along videos on YouTube to help JavaScript newbies.

This is my first post here!

Now lets see how to write a polyfill for document.getElementsByClassName.

Why is it required?

We all know that there are numerous web browsers, and not all the browsers provide all the inbuilt functions. Hence, we write polyfills to make sure that our code works on all the platforms.

We are taking an example of getElementsByClassName for this one.

index.html

Lets create a sample .html file.

  <body>
    <div></div>
    <div>
      <div>
        <div>
          <div>
            <div>
              <header class="wanted"></header>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div>
      <p></p>
      <p>
        <span></span>
        <span class="wanted">Code along with Vishal</span>
        <span></span>
      </p>
      <p class="wanted"></p>
    </div>
    <div class="wanted"></div>
    <div></div>

    <script src="scripts/findByClass.js"></script>
  </body>
Enter fullscreen mode Exit fullscreen mode

we want to write a JS function which would traverse over each of the DOM elements and fetch all the elements with the class wanted.

findByClass.js

Below is my implementation of this polyfill

document.findByClass = function(requiredClass) {
  const root = this.body;

  function search(node) {
    let result = [];

    if(node.classList.contains(requiredClass)) {
      return node;
    }

    for (const element of node.children) {
      result = result.concat(search(element));
    }

    return result;
  }

  return search(root);
}
Enter fullscreen mode Exit fullscreen mode

Now, upon calling document.findByClass('wanted') would return a list of all the elements with the class wanted.

Video tutorial and explanation

Please visit my YouTube channel to watch me writing this code and explaining every step in detail!

IMAGE ALT TEXT HERE

Show some love! so that I can continue making such videos, and also let me know what else I should talk about?

Discussion (3)

pic
Editor guide
Collapse
eddsaura profile image
Jose E Saura

Is there any browser out there that dpesn't support getElementsByClassName? Damn

Collapse
vishal0203 profile image
Vishal Sharma Author

Haha, I think every browser does support it. But I'm just giving an example why polyfills are important. Plus, these kind of questions do pop up in Front-end developer interviews.

Collapse
eddsaura profile image
Jose E Saura

Nice to know! ✨🤘🏼