I want to find all spans in a document that have the “email” attribute and then for each email address i’ll check with my server if the email is approved and inject to the span
content an img with a “yes” or a “no”. I don’t need the implementation of the PHP side, only JavaScript.
So say “newsletter@zend.com” is approved in my db and the HTML code is:
<span dir="ltr"><span class="yP" email="newsletter@zend.com">Zend Technologies</span></span>
Then the JavaScript will change the HTML to:
<span dir="ltr"><span class="yP" email="newsletter@zend.com"><img src="yes.gif" />Zend Technologies</span></span>
I need someone to guide me to the right direction on how to approach this.
Note: i don’t want to use jQuery.
If you don’t want to use a library, and you don’t want to limit yourself to browsers that support
querySelectorAll, you’re probably best off with a simple recursive-descent function orgetElementsByTagName. Here’s an RD example:The function (off-the-cuff, untested):
Calling it:
Alternately, if you want to rely on
getElementsByTagName(which is quite widely supported) and don’t mind building such a largeNodeListin memory, that would be simpler and might be faster: It would let you get one flatNodeListof allspanelements, so then you’d just have a simple loop rather than a recursive-descent function (not that the RD function is either difficult or slow, but still). Something like this:You’ll want to compare and decide which method suits you best, each probably has pros and cons.
References:
However, for this sort of thing I really would recommend getting and using a good JavaScript library like jQuery, Prototype, YUI, Closure, or any of several others. With any good library, it can look something like this (jQuery):
…or this (Prototype):
…and the others won’t be massively more complex. Using a library to factor our common ops like searching for things in the DOM lets you concentrate on the actual problem you’re trying to solve. Both jQuery and (recent versions of) Prototype will defer to
querySelectorAllon browsers that support it (and I imagine most others will, too), and fall back to their own search functions on browsers that don’t.