JL.
JL.

Reputation: 81262

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

I would like to find all occurrence of the $ character in the dom, how is this done?

Upvotes: 2

Views: 628

Answers (5)

Geek Num 88
Geek Num 88

Reputation: 5312

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

Upvotes: -1

Tim Down
Tim Down

Reputation: 324547

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

Upvotes: 1

gnarf
gnarf

Reputation: 106332

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"]

Upvotes: 1

harto
harto

Reputation: 90493

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.

Upvotes: 1

Richard JP Le Guen
Richard JP Le Guen

Reputation: 28753

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.

Upvotes: 4

Related Questions