js判断一个元素是否包含另外一个元素

/*

Bits    Number    Meaning
000000     0        
元素一致
000001     1        节点在不同的文档(或者一个在文档之外)
000010     2        节点 B 在节点 A 之前
000100     4        节点 A 在节点 B 之前
001000     8        节点 B 包含节点 A
010000     16    节点 A 包含节点 B
100000     32    浏览器的私有使用
*/

//obj.contains ? obj.contains(event.toElement) : obj.compareDocumentPosition(event.relatedTarget)
/*window.onload = function () {
var A = document.getElementById('parent'),
B = document.getElementById('child');
alert(A.compareDocumentPosition(B)); //B与A不相连,B在A的后面,A包含B 4+16 = 20
alert(B.compareDocumentPosition(A)); //A与B不相连,A在B的前面,A包含B 2+8 = 10

}*/

在IE 下有自带的contains函数,但firefox默认没有,以下是在firefox做的一个扩展,如果包含反回true,否则反回false。


if (typeof (HTMLElement) != "undefined") {
    HTMLElement.prototype.contains = function (o) {
        return this.compareDocumentPosition(o) == 20 ? true : false;

原文地址:https://www.cnblogs.com/canphp/p/2423270.html