Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

cross browser code for finding class attribute of anchors

Status
Not open for further replies.

toolkit

Programmer
Aug 5, 2001
771
GB
Hi there. Was wondering if anyone could help me on this (hopefully straightforward) question:

I have a test function that accepts an element parameter, and attempts to use DOM to find all child anchor elements below this node, and then find the class attribute for each anchor. The code should look like:
Code:
function showChildrendAnchorClasses(var inputElement) {
    var nodeList = inputElement.element.getElementsByTagName("a");
    for (var i = 0; i < nodeList.length; i++) {
        var node = node.item(i);
        // what must I do to coerce/cast the Node to an Element?
        var elem = ??
        alert(elem.getAttribute("class"));
    }
}
The list returned from getElementsByTagName contains objects that satisfy the Node DOM contract. This Node object does not contain a getAttribute method, whereas Element does. To get this to work with IE, I had to use:
Code:
function showChildrendAnchorClasses(var inputElement) {
    var nodeList = inputElement.element.getElementsByTagName("a");
    for (var i = 0; i < nodeList.length; i++) {
        var node = node.item(i);
        alert(node.className);
    }
}
But I'm not sure how cross-browser friendly that solution is? Its been a while since I used Javascript, so I'm probably missing something obvious?

Thanks, Neil
 

Change this:

Code:
var node = node.item(i);

to this:

Code:
var node = nodeList[loop];

Hope this helps,
Dan


[tt]D'ya think I got where I am today because I dress like Peter Pan here?[/tt]
[banghead]

 
toolkit,

I think node.className is cross-browser support. If any problem arises, it is probably due to other statements. I would make these changes and it would make the function cross-browser.
[tt]
function showChildrendAnchorClasses(inputElement) {
var nodeList = inputElement.getElementsByTagName("a");
for (var i = 0; i < nodeList.length; i++) {
var node = nodeList;
alert(node.className);
}
}
[/tt]
regards - tsuji
 
Sorry - and this:

Code:
inputElement.element.

to this:

Code:
inputElement.

as tsuji has shown.

Dan

[tt]D'ya think I got where I am today because I dress like Peter Pan here?[/tt]
[banghead]

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top