Skip to content
Advertisement

why js closest method not find sibling element?

Note: as far as i know that closest() method searches up the DOM tree for the closest element which matches a specified CSS selector.

When i click on margin space between two li element .. it’s return null… but if i replace margin-bottom: 15px; with padding-bottom… everything is okay…

CSS Code

JavaScript

Image if i click on red mark area.. it’s not found sibling li element ..

enter image description here

Example Code

JavaScript
JavaScript
JavaScript

Advertisement

Answer

.closest() method only traverses parents, not children.

That area is in container .amenities-filters-inner not inside list element, so it won’t find the .amenities-id.

Change the background color of container to debug.

JavaScript

If you don’t want gaps between list items, don’t use margin. Use padding-top and padding-bottom instead.

The closest() method traverses the Element and its parents (heading toward the document root) until it finds a node that matches the provided selector string. Will return itself or the matching ancestor. If no such element exists, it returns null.

https://developer.mozilla.org/en-US/docs/Web/API/Element/closest

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement