Re: Native DOM way to get nodes of arbitrary type/name

On Fri, Oct 4, 2013 at 2:27 PM, Marat Tanalin <mtanalin@yandex.ru> wrote:

>     * For example, server-side script could minify HTML code
>       by removing all HTML comments as DOM nodes. (DOM is not
>       about just JavaScript inside browser. DOM can be used
>       on server side for arbitrary DOM-tree modifications.)
>

Browser specifications only target JavaScript inside browsers.  Other
environments can define their own additions, but it's not something specs
like HTML and DOM try to tackle.  (They have enough work to do already, and
browsers are unlikely to spend time implementing APIs that nobody needs on
the Web.)

    * Another usecase is processing text nodes via JavaScript
>       in browser.
>

FYI, a use case is something you want to accomplish, such as "modify all
text on a web site to be in alternating caps".  (That's not a use case for
this, of course--that'd be CSS's job.)  Given that, can you give a concrete
use case?

I don't know the use cases, so I don't know if any API should be added, but
here's how you can do this without manually recursing yourself.  Note that
you may be surprised by the results of "all text nodes".  For example,
it'll include inline scripts.

    var getAllWalkerResults = function(walker)
    {
        var result = [];
        while(walker.nextNode())
            result.push(walker.currentNode);
        return result;
    }

    var getAllTextElements = function(element) { return
getAllWalkerResults(document.createTreeWalker(element,
NodeFilter.SHOW_TEXT)); }
    var getAllCommentElements = function(element) { return
getAllWalkerResults(document.createTreeWalker(element,
NodeFilter.SHOW_COMMENT)); }
    console.log(getAllTextElements(document));
    console.log(getAllCommentElements(document));

-- 
Glenn Maynard

Received on Friday, 4 October 2013 19:58:47 UTC