Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/ziggi/dom-parents
Get the parents of the element, optionally filtered by a selector.
https://github.com/ziggi/dom-parents
Last synced: 14 days ago
JSON representation
Get the parents of the element, optionally filtered by a selector.
- Host: GitHub
- URL: https://github.com/ziggi/dom-parents
- Owner: ziggi
- License: mit
- Created: 2018-02-23T17:58:08.000Z (almost 7 years ago)
- Default Branch: master
- Last Pushed: 2023-12-05T20:05:25.000Z (about 1 year ago)
- Last Synced: 2025-01-24T07:17:15.749Z (15 days ago)
- Language: JavaScript
- Size: 7.81 KB
- Stars: 5
- Watchers: 3
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# dom-parents
Get the parents of the element, optionally filtered by a selector.
## Install
```sh
npm install --save dom-parents
```## Examples
### Apply action to all parent elements
```js
import getParents from 'dom-parents';getParents(document.querySelector('#main'), '.cat').forEach((element) => {
element.style.backgroundColor = '#008800';
})
```### Check the existence of parents
```js
import getParents from 'dom-parents';document.querySelectorAll('.animal').forEach((element) => {
element.addEventListener('mousedown', () => {
const isBobAnAnimal = getParents(this, '.animals').length !== 0;
if (isBobAnAnimal) {
console.log('Bob is animal');
} else {
console.log('Bob is spy!');
}
});
});
```### If the user clicks on an `.item` element
```js
import getParents from 'dom-parents';document.addEventListener('mousedown', (event) => {
const [item] = getParents(event.target, '.item', true);
if (item) {
console.log('mousedown on .item element');
}
});
```## API
### getParents(element, selector, includeElement = false)
Returns the parents of the element, optionally filtered by a selector.
#### element
Type: `object`
The element from which the search should start.
#### selector
Type: `string`
Selector to search for the parent elements.
#### includeElement
Type: `bool`
Default: `false`
Include `element` to the search or not.