Javascript Code QuerySelector to Find/Get Parent Element

Javascript Code How to Use document.querySelector() to Get a Parent of the Element that is the Target of the querySelector() via the Closest() method

Home Short:

The code below allows you to perform a document.querySelector on an element and get a handle to one of the elements parent elements.

Now if you are sure the parent element you want to get the handle to is the immediate parent up the nodelist you can simply run the following JavaScript code:

But what if you are not sure the target element you are seeking is just one node up? In this case use the JavaScript method closest()

The above example assumes you are looking for div element so you simply replace that with the next element up the nodelist you are looking for, ie "img" for image or "table" for table, etc. You can also use id or class values as well.

S
H
A
R
E