Skip to content
← Writing

1 min read

Tool to check if parent elements have certain properties

A simple recursive tool to check element's parents.

I work on a lot of different sites, making content that sits deep down in the DOM. When elements aren't behaving as I wish it's often due to its parents' CSS properties: an overflow: hidden stopping position: fixed working, or a transform stopping position: sticky doing what it should.

To quickly diagnose what's going on, on sites I'm not too familiar with, I use this little JS tool in the console:

let parent = document.querySelector(".my-element").parentElement;
while (parent) {
const hasProperty = getComputedStyle(parent).overflow;
if (hasProperty !== "") {
console.log(hasProperty, parent);
}
parent = parent.parentElement;
}


This recursive loop is handy for lots of jobs, such as if you want to check if your child element is a decendant of a particular HTML tag, and do something if so:

let parent = document.querySelector(".my-element").parentElement;
while (parent) {
if (parent.tagName === "ARTICLE") {
// make the change you want
}
parent = parent.parentElement;
}