SimpleSelector, Javascript DOM selector


/ Published in: JavaScript
Save to your folder(s)

SimpleSelector is a small DOM selector object with support for the most used selectors. It's also the default selector for the jLim JavaScript framework.

Why use SimpleSelector?
- very small, less than 2kb minified
- easy to use with $$()
- no overhead, no functions you hardly ever use
- ideal for smaller websites


Copy this code and paste it in your HTML
  1. /**
  2.  * SimpleSelector ($$)
  3.  *
  4. * @fileOverview
  5.  * SimpleSelector is a small DOM selector object with support for the
  6.  * most used selectors, like:
  7.  * - By id: $$('#wrap')
  8.  * - By class: $$('.special')
  9.  * - By tag: $$('p')
  10.  * - Mulitple: $$('#id, .cls')
  11.  * - Give context: $$('a', '#wrap') or $$('#wrap a')
  12.  * Released under MIT license.
  13.  * @version 1.1.0
  14.  * @author Victor Villaverde Laan
  15.  * @link http://www.freelancephp.net/simple-css-selector-function/
  16.  * @link https://github.com/freelancephp/SimpleSelector
  17.  */
  18. (function (window) {
  19.  
  20. var SimpleSelector = window.SimpleSelector = {
  21.  
  22. /**
  23. * Selector function
  24. * @param {String} selector
  25. * @param {String|DOMElement|DOMElement[]} [context=window.document]
  26. * @return {DOMElement[]}
  27. */
  28. select: function (selector, context) {
  29. var s = selector,
  30. c = context,
  31. els = [];
  32.  
  33. // prepare selector
  34. s = s.split(',');
  35.  
  36. // prepare context
  37. c = isObjType(c, 'String') ? $$(c) : c && c.length ? c : window.document;
  38.  
  39. // make array
  40. if (!isObjType(c, 'Array'))
  41. c = [c];
  42.  
  43. // loop through given contexts
  44. for (var i in c) {
  45. // loop through given selectors
  46. for ( var j in s) {
  47. var strim = s[j].replace(/\s+/g, ''),
  48. sp = s[j].split(' '),
  49. op = strim.substr(0, 1),
  50. name = strim.substr(1),
  51. tels = [],
  52. nextContext;
  53.  
  54. if (sp.length > 1) {
  55. // make recursive call to handle f.e. "body div p strong"
  56. nextContext = $$(sp[0], c[i]);
  57. tels = $$(sp.slice(1).join(' '), nextContext);
  58. els = els.concat(tels);
  59. } else if (op == '#') {
  60. // by id
  61. tels[0] = c[i].getElementById ? c[i].getElementById(name) : window.document.getElementById(name);
  62.  
  63. // check if founded array is part of context
  64. if (tels[0] && SimpleSelector.isDescendant(tels[0], c[i]))
  65. els.push(tels[0]);
  66. } else if (op == '.') {
  67. // by className
  68. var expr = new RegExp('(^|\\s)'+ name +'(\\s|$)'),
  69. all = c[i].getElementsByTagName('*');
  70.  
  71. // filter all elements that contain the given className
  72. for (var v = 0, w = all.length; v < w; v++) {
  73. if (expr.test(all[v].className))
  74. els.push(all[v]);
  75. }
  76. } else {
  77. // by tagName
  78. tels = c[i].getElementsByTagName(strim);
  79.  
  80. // add all founded elements
  81. for (var y = 0, z = tels.length; y < z; y++)
  82. els.push(tels[y]);
  83. }
  84. }
  85. }
  86.  
  87. // return array of elements
  88. return SimpleSelector.clearDuplicates(els);
  89. },
  90.  
  91. /**
  92. * Check if node is part of root element
  93. * @param {DOMElement} descendant
  94. * @param {DOMElement} ancestor
  95. * @return {Boolean}
  96. */
  97. isDescendant: function (descendant, ancestor) {
  98. return descendant.parentNode == ancestor || descendant.tagName.toUpperCase() != 'HTML' && SimpleSelector.isDescendant(descendant.parentNode, ancestor);
  99. },
  100.  
  101. /**
  102. * Check if item exists in array
  103. * @param {Array} arr
  104. * @param {Mixed} item
  105. * @return {Boolean}
  106. */
  107. itemExists: function (arr, item) {
  108. for (var j = 0, max = arr.length; j < max; j++) {
  109. if (arr[j] === item)
  110. return true;
  111. }
  112.  
  113. return false;
  114. },
  115.  
  116. /**
  117. * Clear duplicate items out of array
  118. * @param {Array} arr
  119. * @return {Array} Cleared array
  120. */
  121. clearDuplicates: function (arr) {
  122. var a = [];
  123.  
  124. for (var i = 0, max = arr.length; i < max; i++) {
  125. if (!SimpleSelector.itemExists(a, arr[i]))
  126. a.push(arr[i]);
  127. }
  128.  
  129. return a;
  130. }
  131.  
  132. };
  133.  
  134. /**
  135.  * @private
  136.  */
  137. function isObjType (o, type) {
  138. return Object.prototype.toString.call(o) === '[object '+ type +']';
  139. };
  140.  
  141. if (!window.$$) {
  142. /**
  143. * Add short name for SimpleSelector method
  144. * @function
  145. */
  146. window.$$ = SimpleSelector.select;
  147. }
  148.  
  149. })(window);

URL: http://www.freelancephp.net/simpleselector-javascript-dom-selector/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.