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 ); }