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开发者_如何学C: ' + 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.
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);
}
});
.hasClass()
can be used for testing if a specific class is among the classes assigned to the element. Will return either true or false.
$(node).hasClass('myclass')
Or you can use .attr()
to get the class
attribute of an element.
var klassz=$(node).attr('class');
Instead of the latter, you can simply use node.className
either.
Checkout http://jsfiddle.net/tahir/7gfuT/
This code is using DOM directly (just to clarify the concepts). You can use jquery wrapper functions as suggested by bazmegakapa to simplify the access to DOM attributes
精彩评论