Handling NodeLists & HTMLCollection in Regular JavaScript vs Sniper.js
Regular JavaScript
document.getElementsByClassName("button")// returns HTMLCollections
document.querySelectorAll(".button")// returns NodeList
Let's say you want to give all the selected elements a class name of 'active'
, in regular javscript. Obviously you'll need to loop through it and perform for your actions for each on the elements. like this:
let mybuttons = document.getElementsByClassName("button");
//to use forEach loop you'll have to convert it an actual array otherwise use the for-loop
let arrayOfbutons = Array.from(mybuttons);
arrayOfbutons.forEach((element)=>{
element.classList.add("active");
})
Vs SniperJs
sniper.js takes the hassle of having select and then loop through the elements to apply action to them. sniper.js allows you to apply your action(s) to multiple elements in one selection.
//this will add active to all the matched elements
$(".button*").addClass('active');
👉 When using SniperJs you don't need to worry about HTMLCollections, NodeLists or other array-like lists. Just go ahead apply your actions
//this will remove all the matched elements at once (no need for loops)
$("#nav > .button*").remove();
Last updated