JavaScript closest
When it comes to finding relationships between elements, we traditionally think of a top-down approach. We can thank CSS and querySelector
/querySelectorAll
for that relationship in selectors. What if we want to find an element's parent based on selector?
To look up the element tree and find a parent by selector, you can use HTMLElement
's closest
method:
// Our sample element is an "a" tag that matches ul > li > a
const link = document.querySelector('li a');
const list = a.closest('ul');
closest
looks up the ancestor chain to find a matching parent
element -- the opposite of traditional CSS selectors. You can provide closest
a simple or complex selector to look upward for!
I spent a few months experimenting with different approaches for writing simple, elegant and maintainable media queries with Sass. Each solution had something that I really liked, but I couldn't find one that covered everything I needed to do, so I ventured into creating my...
Regardless of your stance on pornography, it would be impossible to deny the massive impact the adult website industry has had on pushing the web forward. From pushing the browser's video limits to pushing ads through WebSocket so ad blockers don't detect them, you have...
It's best practice to provide an indicator of some sort when performing an AJAX request or processing that takes place in the background. Since the dawn of AJAX, we've been using colorful spinners and imagery as indicators. While I enjoy those images, I am...
I've been working with the Magento eCommerce solution a lot lately and I've taken a liking to a technique they use with the top bar within their administrative control panel. When the user scrolls below a specified threshold, the top bar becomes attached to the...