Cover Image for Tool to check if parent elements have certain properties

Tool to check if parent elements have certain properties

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:

1 let parent = document.querySelector(".my-element").parentElement;
2 while (parent) {
3 const hasProperty = getComputedStyle(parent).overflow;
4 if (hasProperty !== "") {
5 console.log(hasProperty, parent);
6 }
7 parent = parent.parentElement;
8 }


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:

1 let parent = document.querySelector(".my-element").parentElement;
2 while (parent) {
3 if (parent.tagName === "ARTICLE") {
4 // make the change you want
5 }
6 parent = parent.parentElement;
7 }
8