24 Modern ES6 Code Snippets to Solve Practical JavaScript Problems

Useful snippets to keep in a file for quick reference

Madza
The Startup

--

Title Image

Here I have hand-picked some of the most useful code snippets from 30 seconds of code. It’s an awesome resource, go ahead and show it some love.

In this article I tried to sort them based on their practical use, answering common questions you may face in your project:

1.How to hide all elements specified?

const hide = (...el) => [...el].forEach(e => (e.style.display = 'none'));

// Example
hide(document.querySelectorAll('img')); // Hides all <img> elements on the page

2.How to check if the element has the specified class?

const hasClass = (el, className) => el.classList.contains(className);

// Example
hasClass(document.querySelector('p.special'), 'special'); // true

3.How to toggle a class for an element?

const toggleClass = (el, className) => el.classList.toggle(className);

// Example
toggleClass(document.querySelector('p.special'), 'special');
// The paragraph will not have the 'special' class anymore

4.How to get the scroll position of the current page?

const getScrollPosition = (el = window) => ({
x

--

--

Madza
The Startup

Sharing the latest AI insights, essential tools, and productivity secrets to fuel your career growth!