Monday, December 4, 2023
 Popular · Latest · Hot · Upcoming
rated 0 times [  150] [ 4]  / answers: 1 / hits: 43017  / 15 Years ago, tue, april 14, 2009, 12:00:00

how can i search an html page for a word fast?
and how can i get the html tag that the word is in? (so i can work with the entire tag)

More From » html


To find the element that word exists in, you'd have to traverse the entire tree looking in just the text nodes, applying the same test as above. Once you find the word in a text node, return the parent of that node.

var word = foo,
queue = [document.body],
while (curr = queue.pop()) {
if (!curr.textContent.match(word)) continue;
for (var i = 0; i < curr.childNodes.length; ++i) {
switch (curr.childNodes[i].nodeType) {
case Node.TEXT_NODE : // 3
if (curr.childNodes[i].textContent.match(word)) {
// you might want to end your search here.
case Node.ELEMENT_NODE : // 1

this works in Firefox, no promises for IE.

What it does is start with the body element and check to see if the word exists inside that element. If it doesn't, then that's it, and the search stops there. If it is in the body element, then it loops through all the immediate children of the body. If it finds a text node, then see if the word is in that text node. If it finds an element, then push that into the queue. Keep on going until you've either found the word or there's no more elements to search.

[#99707] Tuesday, April 7, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.

Total Points: 153
Total Questions: 102
Total Answers: 98

Location: Mauritania
Member since Sun, Oct 17, 2021
2 Years ago
lawrencem questions