contains基本兼容
用法node.contains( otherNode )
compareDocumentPosition感受比較奇怪,聽說是這樣node
The Node.compareDocumentPosition() method compares the position of the
current node against another node in any other document.
返回值分爲6個數字
jquery的selector-native有個原生方法contains這樣寫的python
contains: function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && adown.contains(bup) ); }
比較容易理解jquery
開發鳳凰焦點項目的時候,有用到判斷元素包含關係的contains,當時第一反應是想到jquery取子元素的方式.(以前看過實現方式的,忘了2333...)固然不是用的contains,由於相比取子元素更適合關係判斷.那麼jq是怎麼取的呢?git
jQuery.extend({ //direction dir: function( elem, dir, until ) { var matched = [], truncate = until !== undefined; while ( (elem = elem[ dir ]) && elem.nodeType !== 9 ) { if ( elem.nodeType === 1 ) { //nodeType:1 --> element if ( truncate && jQuery( elem ).is( until ) ) { break; } matched.push( elem ); } } return matched; }, sibling: function( n, elem ) { var matched = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { matched.push( n ); } } return matched; } });
siblings: function( elem ) { return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }