<pedrocorreia.net ⁄>
corner
<mySearch ⁄> <mySearch ⁄>

corner
 
corner
<mySnippets order="rand" ⁄> <mySnippets order="rand" ⁄>

corner
 
corner
<myContacts ⁄> <myContacts ⁄>

<email ⁄>


pc@pedrocorreia.net

<windows live messenger ⁄>


pedrojacorreia@hotmail.com

<myCurriculum type="pdf" ⁄>


Download
corner
 
corner
<myBlog show="last" ⁄> <myBlog show="last" ⁄>

corner
 
corner
<myNews show="rand" ⁄> <myNews show="rand" ⁄>

corner
 
corner
<myNews type="cat" ⁄> <myNews type="cat" ⁄>

corner
 
corner
<myQuote order="random" ⁄> <myQuote order="random" ⁄>

corner
 
corner
<myPhoto order="random" ⁄> <myPhoto order="random" ⁄>

<pedrocorreia.net ⁄>
corner
 
corner
<myAdSense ⁄> <myAdSense ⁄>

corner
 
corner
<myVisitorsMap ⁄> <myVisitorsMap ⁄>

corner
 
 

<getElementsByClassName by Walking down the DOM ⁄ >




clicks: 13667 13667 2009-08-02 2009-08-02 goto mySnippets mySnippets javascript  Download  Bookmark This Bookmark This



In JavaScript we have a few methods to get html objects, such as getElementById, getElementsByName, getElementsByTagName, normally these methods will be enough, but what if want to get all elements but by their class name? Well, easy, we build one.



All modern javascript framework have that already built-in, in jQuery is just as easy as $(".mClass"), in this snippet I'll try to show a possible manner to get all elements by their class name, getElementsByClassName.


So we'll examine all the DOM (in this example under document.body), and check all objects class name, if it matches our search than we'll add it to an array.
After retrieving that array we can do whatever we want to it, to give a few examples I also built a few DOM methods.




BasicDom.js, this class will allow us to make some simple changes in DOM, it receives an array with the elements that we want to modify. For example we can Capitalize and Reverse strings, apply Css styles, set inner html in allowed elements.

  1. /**
  2. * This class will allow us to make some simple operations
  3. * in a given Dom Tree
  4. *
  5. * @author: pedrocorreia.net
  6. */
  7. var BasicDom = function(dom) {
  8.  
  9. //cache DOM
  10. var _dom = dom;
  11.  
  12. /**
  13. * Check if we have a valid Dom tree
  14. *
  15. * @return Bool
  16. */
  17. var _isDomTreeValid = (function() {
  18. for (var el in _dom) {
  19. if (el && !_dom[el].tagName) {
  20. return;
  21. }
  22. }
  23. return true;
  24. })();
  25.  
  26. //check if our dom tree's valid
  27. if (!_isDomTreeValid) { throw "DomTree empty or nor valid"; }
  28.  
  29. /**
  30. * Set CSS attributes
  31. *
  32. * @param Object Properties key=>value
  33. * @return this
  34. */
  35. var _css = function(prop) {
  36. var _styles = [];
  37.  
  38. for (var p in prop) {
  39. if (p) { _styles.push(p + ":" + prop[p] + ";"); }
  40. }
  41.  
  42. var style = _styles.join(" ");
  43. for (var el in _dom) {
  44. if (el) {
  45. try {_dom[el].style.cssText = style;}
  46. catch (ex) { }
  47. }
  48. }
  49. return this;
  50. };
  51.  
  52. /**
  53. * Set object inner html value
  54. *
  55. * @param Object
  56. * @param String Value
  57. * @return this
  58. */
  59. var _innerHtml = function(o, v) {
  60. var _invalid = ["COL", "COLGROUP", "FRAMESET", "HTML", "STYLE",
  61. "TABLE", "TBODY", "TFOOT", "THEAD", "TITLE", "TR"].join();
  62.  
  63. if (_invalid.indexOf(o.tagName) < 0) {
  64. try { o.innerHTML = v; }
  65. catch (ex) { }
  66. }
  67. };
  68.  
  69. /**
  70. * Set html content
  71. *
  72. * @param String Text
  73. * @return this
  74. */
  75. var _html = function(txt) {
  76. for (var el in _dom) {
  77. if (el) { _innerHtml(_dom[el], txt); }
  78. }
  79. return this;
  80. };
  81.  
  82. /**
  83. * Reverse String
  84. *
  85. * @return this
  86. */
  87. var _reverse = function() {
  88. for (var el in _dom) {
  89. if (el) {
  90. _innerHtml(_dom[el], _dom[el].innerHTML
  91. .split("")
  92. .reverse()
  93. .join("")
  94. );
  95. }
  96. }
  97. return this;
  98. };
  99.  
  100. /**
  101. * Capitalize Words
  102. *
  103. * @return this
  104. */
  105. var _capitalize = function() {
  106. var arr = [];
  107. for (var el in _dom) {
  108. if (el) {
  109. arr = _dom[el].innerHTML.toLowerCase().split(" ");
  110. for (var i = 0, count = arr.length; i < count; i++) {
  111. arr[i] = arr[i].charAt(0).toUpperCase() + arr[i].slice(1);
  112. }
  113. _innerHtml(_dom[el], arr.join(" "));
  114. }
  115. }
  116. return this;
  117. };
  118.  
  119. /**
  120. * @return Function Css
  121. * @return Function Html
  122. * @return Function Reverse
  123. * @return Function Capitalize
  124. * @return Boolean Is Dom Tree Valid?
  125. * @return Object Dom tree
  126. **/
  127. return {
  128. Css: _css,
  129. Html: _html,
  130. Reverse: _reverse,
  131. Capitalize: _capitalize,
  132. IsValid: _isDomTreeValid,
  133. Dom: _dom
  134. };
  135. };








getElementsByClassName, this is our main class. I used a recursive approach by walking down the DOM, we have many ways to get, other one was to use document.getElementsByTagName("*");

  1. /**
  2. * Filter html elements by its correspondent class name
  3. * This will follow a recursive approach
  4. *
  5. * @return Object Dom Tree
  6. */
  7. var getElementsByClassName = function(cls) {
  8.  
  9. //elements array
  10. var _elems = [];
  11.  
  12. /**
  13. * Walking down Dom Tree
  14. * Recursive Approach
  15. *
  16. * @param Object Node
  17. */
  18. (function(start_node) {
  19. if (!start_node) { start_node = document.body; }
  20. var node = "";
  21.  
  22. for (var i = 0, count = start_node.childNodes.length; i < count; i++) {
  23. node = start_node.childNodes[i];
  24.  
  25. if (node.hasChildNodes()) {
  26. arguments.callee(node); //recursive call
  27. }
  28.  
  29. if (node.className && node.className.indexOf(cls) >= 0) {
  30. _elems.push(node);
  31. }
  32. }
  33. })();
  34.  
  35. return _elems;
  36. };



Init.js, our startup script. In here we'll have two different ways to use getElementsByClassName, by using BasicDom class or just iterate over the array returned by getElementsByClassName, each one's a valid way and has the same purposes.

  1. window.onload = function() {
  2. var elems = getElementsByClassName("my_class");
  3.  
  4. try {
  5. BasicDom(elems)
  6. .Css({
  7. color: "#900",
  8. "font-weight": "bold",
  9. "border-bottom": "dotted 1px #900"
  10. })
  11. .Html("Just testing our BasicDom Class")
  12. .Reverse()
  13. .Capitalize();
  14. }
  15. catch (ex) { }
  16.  
  17. //or we can also access each object by just iterating over "elems"
  18. for (var i = 0, count = elems.length; i < count; i++) {
  19. elems[i].style["fontVariant"] = "small-caps";
  20. }
  21.  
  22. };



An example html file

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4. <title>getElementsByClassName</title>
  5.  
  6. <script type="text/javascript" src="getElementsByClassName.js"></script>
  7. <script type="text/javascript" src="BasicDom.js"></script>
  8. <script type="text/javascript" src="Init.js"></script>
  9.  
  10. </head>
  11. <body>
  12.  
  13. <div id="my_div">
  14. <ul>
  15. <li><span class="my_class">1st Item</span></li>
  16. <li><span class="my_class">2nd Item</span></li>
  17. </ul>
  18. </div>
  19.  
  20. <table class="my_class">
  21. <tr>
  22. <td class="my_class">
  23. Table Data ...
  24. </td>
  25. </tr>
  26. </table>
  27.  
  28. </body>
  29. </html>






Regarding our html example file, this is how it will look before applying BasiDom class




After ...





If you have any doubt or found any error, please drop me an email.









clicks: 13667 13667 2009-08-02 2009-08-02 goto mySnippets mySnippets javascript  Download  Bookmark This Bookmark This