In Chapter 3, under the section "Nodes -> Getting Elements", sub-section "getElementsByClassName", the author suggests implementing a custom getElementsByClassName method for JavaScript engines which do not support it natively.
Although most current engines seem to support getElementsByClassName, the code snippet provided in the book for the custom method does not work properly. I re-wrote some of the implementation to get the desired result:
function getElementsByClassName(node, classname){ if(node.getElementsByClassName){ return node.getElementsByClassName(classname); } else { var results = new Array(); var elemsOnPage = document.getElementsByTagName("*"); var len = elemsOnPage.length; var i; for(i = 0; i < len; i++){ if(elemsOnPage[i].className && elemsOnPage[i].className == classname){ results[results.length] = elemsOnPage[i]; } } return results; } }The original code did not check if className was defined and used indexOf instead of a string comparison. Any feedback or suggestions are much appreciated and I will try to pass the information to the authors. You can buy the book here at amazon if you are interested in these topics. I highly recommend it.
No comments:
Post a Comment