Skip to content

Instantly share code, notes, and snippets.

@timbryandev
Last active August 22, 2022 14:21
Show Gist options
  • Save timbryandev/2dc33a0835eb8bcb30e47d92c48b2331 to your computer and use it in GitHub Desktop.
Save timbryandev/2dc33a0835eb8bcb30e47d92c48b2331 to your computer and use it in GitHub Desktop.
List all the classes and ids of all the parents of an element

Use your web browsers' dev tools elements pane and select the element you want to inspect.

Note You must perform this first step before following either of the below two options. This is because the main code uses the $0 browser varable which is assigned to the most receently selected DOM element through the elements tab in your web browser dev tools.

Option 1:

  • Paste this into your web browser console to log all parent element:
var element = $0
while(element.parentElement) {
  var {classList, id, parentElement} = element
  console.group(element)
  id && console.log('id', id)
  classList.length > 0 && console.log('classList', [...classList])
  console.groupEnd()
  element = parentElement
}
  • You'll see your parent selctors in the console logs

Option 2

  • Click and drage this link into your bookmarks to create a bookmarklet <a href="javascript: for(var element=$0;element.parentElement;){var{classList:a,id:b,parentElement:c}=element;console.group(element),b&&console.log("id",b),a.length>0&&console.log("classList",[...a]),console.groupEnd(),element=c};">List all parent selectors

  • You'll see your parent selctors in the console logs

  • Note If you can't see the above anchor tag / link, then create a new bookmark and add the following as the URL:

javascript: for(var element=$0;element.parentElement;){var{classList:a,id:b,parentElement:c}=element;console.group(element),b&&console.log("id",b),a.length>0&&console.log("classList",[...a]),console.groupEnd(),element=c};

Credits

JS has been minified by the fantastic https://www.toptal.com/developers/javascript-minifier ❤️

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment