TheSavior / find-parent

A utility for finding the nearest parent that matches a test function

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

find-parent

Build Status devDependency Status

Find-parent is a utility to help find the closest element up an element's parent tree (possibly including itself) that matches certain rules.

Installation

$ npm install find-parent --save-dev

Usage

The examples below will use this as an example DOM structure.

<div class="foo">
  <span id="test" data-test-node="test">
    <a href="http://google.com">link text</a>
  </span>
</div>

byMatcher(element, func, opts)

var findParent = require('find-parent');

var element = document.getElementsByTagName('a')[0];

var result = findParent.byMatcher(element, function(node) {
  return node.className === 'foo';
});

// result is === to the element <div class="foo">

byClassName(element, className, opts)

var findParent = require('find-parent');

var element = document.getElementsByTagName('a')[0];

var result = findParent.byClassName(element, 'foo');

// result is === to the element <div class="foo">

withDataAttribute(element, attName, opts)

var findParent = require('find-parent');

var element = document.getElementsByTagName('a')[0];

var result = findParent.withDataAttribute(element, 'testNode');

// result is === to the element <span id="test" data-test-node="test">

Options

All findParent functions take an optional options argument.

key value type default description
throwOnMiss boolean false Throw error if no matching parent is found

About

A utility for finding the nearest parent that matches a test function


Languages

Language:JavaScript 100.0%