Post Reply 
Adding contains method to mozilla
Apr. 10, 2006, 12:01 AM
Post: #1
Adding contains method to mozilla
Here's the code I'm trying out:

Code:
// create a contains method for gecko to check if one node is contained in another
// based on http://www.quirksmode.org/blog/archives/2006/01/contains_for_mo.html
// ie & opera have a contains method

function prxContainsCheck(){
  var n=document.documentElement;
  if(typeof(n.contains)=='undefined' && typeof(n.compareDocumentPosition!='undefined')){
    try{
      Node.prototype.contains=function(arg){return !!(this.compareDocumentPosition(arg) & 16)};
    }catch (e){
      alert("create contains method failed");
    }
  }
  // alert(typeof(n.contains));
  // alert(typeof(n.contains(n.firstChild)));
  // alert(n.contains(n.firstChild));
}

prxContainsCheck();

It seems that this would be more efficient than looping or bubbling up through the document, ala BrainJar.

Mike
Add Thank You Quote this message in a reply
Apr. 21, 2006, 09:45 AM
Post: #2
 
Heres the latest version I'm using:

Code:
//-----------------------------------

// create a contains method for mozilla to check if one node is contained in another
// based on http://www.quirksmode.org/blog/archives/2006/01/contains_for_mo.html
// ie & opera have a contains method
// added isSameNode check to make it work like ie & opera

function prxContainsCheck(){
  var n=document.documentElement;
  if(typeof(n.contains)=='undefined' && typeof(n.compareDocumentPosition!='undefined')){
    try{
      Node.prototype.contains=function(arg){return !!(this.compareDocumentPosition(arg) & 16 || this.isSameNode(arg))};
    }catch (e){
      alert("create contains method failed");
    }
  }
}

prxContainsCheck();


//-----------------------------------

IE & Opera return true when a node is compared to itself, so I added the isSameNode check.

This function has turned out to be quite handy.

Mike
Add Thank You Quote this message in a reply
Post Reply 


Forum Jump: