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>
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);
}
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!
Show some love! so that I can continue making such videos, and also let me know what else I should talk about?
Top comments (4)
Is there any browser out there that dpesn't support getElementsByClassName? Damn
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.
Nice to know! ✨🤘🏼
Do u have polyfill for GetElementsById() or it will same just that, it will return the first id it finds?