validate-target

Easily validate target of an HTML element especially during event delegation

Usage no npm install needed!

<script type="module">
  import validateTarget from 'https://cdn.skypack.dev/validate-target';
</script>

README

validateTarget

validateTarget TravisCI Coverage Status Node.js Bundlephobia

validateTarget is a minimalist script to easily validate target of an HTML element especially during event delegation. Event delegation is advised for better performance, read MDN documentation for more information.

No needs to check nodeName or className properties, the function return directly a boolean when the target is correct.

The target can have multiple node name if element shares common code. The function use Element.matches to ensure selectorString match the target.

Installation

The function is available as the validate-target package name on npm and Github.

npm i --save-dev validate-target
yarn add --dev validate-target

Environment

validateTarget was built for Node.js >=8.11.2.

Usage

Basic usage

The following example return true because nodeName and selectorString properties match.

<a href="" class="itemLink">Link</a>
validateTarget({
    target: document.querySelector('.itemLink'),
    selectorString: '.itemLink',
    nodeName: ['a']
});

Multiple node names

The following example return true because button is a granted value for nodeName and selectorString match ().

<a href="" class="itemLink">Link</a>
<button class="itemButton">Button</button>
validateTarget({
    target: document.querySelector('.itemLink'),
    selectorString: '.itemLink',
    nodeName: ['button', 'a']
});

Event delegation

The following example create a click event listener on the nav element and catch click events on itemLink element.

<nav class="nav">
    <ul>
        <li>
            <a href="" class="itemLink">Link</a>
        </li>
        <li>
            <a href="" class="itemLink">Link</a>
        </li>
        <li>
            <a href="" class="itemLink">Link</a>
        </li>
    </ul>
</nav>
document.querySelector('.nav').addEventListener('click', e => {
    const validateTargetLinkClick = validateTarget({
        target: e.target,
        selectorString: '.itemLink',
        nodeName: ['a']
    });

    if (validateTargetLinkClick) {
        console.log('Link is clicked.');
    }
});

Parameters

target

HTMLElement

Tells to the function the target.

selectorString

String

Tells to the function the selector string of the target element. Can be any valid CSS selector (class, id, attribute, etc.). The function uses Element.matches function.

nodeName

String || Array

Tells to the function the node name in a string or a list of possible node names in an array. The order of the parameters in the array does not matter.

Licence

validateTarget is licensed under the MIT License.

Created with ♥ by @yoriiis.