It is a common thing to detect whether an element node is a child of another element in web development, which makes it easier for us to judge method events, yet many people do not know the element.classlist API, For example, classname management requires a specific JavaScript toolkit to complete, but a method such as detecting whether an element node is a child of another element can only be done by means of a tool or a cyclic detection contains, in fact the following code can:
| The code is as follows |
Copy Code |
function (ParentNode, Childnode) { If (' contains ' in parentnode) { Return Parentnode.contains (Childnode); } else { Return parentnode.comparedocumentposition (childnode)% 16; } }
|
You'll notice our check contains before using it, you might think, with little known comparedocumentposition in this case, contains not supported (Firefox < 9). This approach would be useful when creating a list between a drag-and-drop control and a determined action.
Add: How jquery determines whether the current element is a child of a node
| The code is as follows |
Copy Code |
$ (node). Click (function () { if ($ (this). Parents ('. AA '). Length > 0) { is a sub-node under AA class } }); |