Search code examples
javascriptjquerydomdom-traversal

Using jQuery to walk DOM, return HTML attributes from node


I want to walk through the DOM and identify the HTML attributes of certain nodes. For example the class value for all tags.

The following code was suggest by another member of Stackoverflow for walking the DOM: http://jsfiddle.net/FJeaY/

It works well and I can use it to identify the ID of a node and it's parents. It's also pretty easy to filter for hyperlinks:

walk_the_DOM(document.body, function(node) {
    if(node.nodeName == "A")
        alert(node.nodeName + ' id: ' + node.id);
});

However I am unsure what to use to identify the class (or any other HTML attribute). Everything I've tried so far from searching the jQuery documentation has failed.

Any ideas appreciated, thank you in advance.


Solution

  • The function in question actually does not use jQuery at all and the jQuery documentation is not suited for learning about the DOM in general.

    Have a look at the MDC HTMLElement reference. What you want is the className attribute:

    walk_the_DOM(document.body, function(node) {
        if(node.nodeName == "A") {
            alert(node.nodeName + ' class: ' + node.className);
        }
    });