开发者

Javascript search for all occurences of a character in the dom?

开发者 https://www.devze.com 2022-12-31 20:36 出处:网络
I would like to find all occurrence of the $ ch开发者_JAVA百科aracter in the dom, how is this done?You can\'t do something semantic like wrap $4.00 in a span element?

I would like to find all occurrence of the $ ch开发者_JAVA百科aracter in the dom, how is this done?


You can't do something semantic like wrap $4.00 in a span element?

<span class="money">$4.00</span>

Then you would find elements belonging to class 'money' and manipulate them very easily. You could take it a step further...

<span class="money">$<span class="number">4.00</span></span>

I don't like being a jQuery plugger... but if you did that, jQuery would probably be the way to go.


One way to do it, though probably not the best, is to walk the DOM to find all the text nodes. Something like this might suffice:

var elements = document.getElementsByTagName("*");
var i, j, nodes;
for (i = 0; i < elements.length; i++) {
    nodes = elements[i].childNodes;
    for (j = 0; j < nodes.length; j++) {
        if (nodes[j].nodeType !== 3) { // Node.TEXT_NODE
            continue;
        }
        // regexp search or similar here
    }
}

although, this would only work if the $ character was always in the same text node as the amount following it.


You could just use a Regular Expression search on the innerHTML of the body tag:

For instance - on this page:

var body = document.getElementsByTagName('body')[0];
var dollars = body.innerHTML.match(/\$[0-9]+\.?[0-9]*/g)

Results (at the time of my posting):

["$4.00", "$4.00", "$4.00"]


The easiest way to do this if you just need a bunch of strings and don't need a reference to the nodes containing $ would be to use a regular expression on the body's text content. Be aware that innerText and textContent aren't exactly the same. The main difference that could affect things here is that textContent contains the contents of <script> elements whereas innerText does not. If this matters, I'd suggest traversing the DOM instead.

var b = document.body, bodyText = b.textContent || b.innerText || "";
var matches = bodyText.match(/\$[\d.]*/g);


I'd like to add my 2 cents for prototype. Prototype has some very simple DOM traversal functions that might get exactly what you are looking for.

edit so here's a better answer

the decendants() function collects all of the children, and their children and allows them to be enumerated upon using the each() function

$('body').descendants().each(function(item){
   if(item.innerHTML.match(/\$/))
   {
      // Do Fun scripts
   }
});

or if you want to start from document

 Element.descendants(document).each(function(item){
   if(item.innerHTML.match(/\$/))
   {
      // Do Fun scripts
   }
});
0

精彩评论

暂无评论...
验证码 换一张
取 消