parent-child nesting validation for html elements

This is not a full blown HTML spec validation (intentionally). The parent-child nesting is considered valid if browser does not modify it, regardless of whether or not HTML spec considers it valid or invalid. So, the library is purely for detecting the kind of element nesting which result in altered DOM.



browser modifies the above shown structure to below shown structure, which is why the library considers the p > hr nesting invalid.

<hr />

And though <h1> <div> hi </div> </h1> markup is technically invalid as per HTML spec, it’s still considered valid because the browser does not modify it, so h1 > div nesting is considered valid by the library.


npm i validate-html-nesting


isValidHTMLNesting(parentTag: string, childTag: string) : boolean

Usage Example

import { isValidHTMLNesting } from 'validate-html-nesting';

isValidHTMLNesting('a', 'a'); // false
// because <a> can not be child of <a>

isValidHTMLNesting('p', 'hr'); // false
// because <hr> can not be child of <p>

isValidHTMLNesting('div', 'a'); // true
// because <a> can be child of <div>

See also

Who is this library for?

This library is mostly useful for UI framework authors who need a way to make sure that DOM structure rendered by the browser matches the authored markup so that there’s no unexpected behaviors

Test Suite

Refer to validation.test.js to see full test suite


PR’s are welcome. Create an issue if you found a bug.


View Github