Created
July 11, 2012 16:36
-
-
Save Naouak/270df7ee30bc232e77b6 to your computer and use it in GitHub Desktop.
TextNode near Input finder
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function(){ | |
function nativeTreeWalker() { | |
var walker = document.createTreeWalker( | |
document.body, | |
NodeFilter.SHOW_TEXT, | |
null, | |
false | |
),node,textNodes = []; | |
while (node = walker.nextNode()) { | |
if (node.nodeValue) { | |
textNodes.push(node); | |
} | |
} | |
return textNodes; | |
} | |
function collide(b1,b2){ | |
return !(b1.x+b1.w < b2.x) | |
&& | |
!(b1.x > b2.x+b2.w) | |
&& | |
!(b1.y+b1.h < b2.y) | |
&& | |
!(b1.y > b2.y+b2.h); | |
} | |
function coords(element) { | |
var x = 0,y = 0,obj = { | |
w:element.offsetWidth,h:element.offsetHeight | |
}; | |
while (element.offsetParent) { | |
x += element.offsetLeft; | |
y += element.offsetTop; | |
element = element.offsetParent; | |
} | |
return {x:x,y:y,w:obj.w,h:obj.h}; | |
} | |
var textNodes = nativeTreeWalker(),nodes = document.querySelectorAll("input[type=text]"),nodec; | |
for (var i = nodes.length - 1; i >= 0; i--) { | |
nodec = coords(nodes[i]); | |
nodec.x-=100; | |
nodec.y-=100; | |
nodec.w+=200; | |
nodec.h+=200; | |
console.log(nodes[i]); | |
for (var j = textNodes.length - 1; j >= 0; j--) { | |
if (textNodes[j].nodeValue.trim().length > 0 && collide(nodec,coords(textNodes[j].parentNode))) { | |
console.log(textNodes[j].nodeValue); | |
//uncomment this line to get a graphical result | |
//textNodes[j].parentNode.style.border = "solid red 2px"; | |
} | |
}; | |
}; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment