You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

87 lines
2.4 KiB

4 years ago
  1. var ElementType = require("domelementtype");
  2. var isTag = exports.isTag = ElementType.isTag;
  3. exports.testElement = function(options, element){
  4. for(var key in options){
  5. if(!options.hasOwnProperty(key));
  6. else if(key === "tag_name"){
  7. if(!isTag(element) || !options.tag_name(element.name)){
  8. return false;
  9. }
  10. } else if(key === "tag_type"){
  11. if(!options.tag_type(element.type)) return false;
  12. } else if(key === "tag_contains"){
  13. if(isTag(element) || !options.tag_contains(element.data)){
  14. return false;
  15. }
  16. } else if(!element.attribs || !options[key](element.attribs[key])){
  17. return false;
  18. }
  19. }
  20. return true;
  21. };
  22. var Checks = {
  23. tag_name: function(name){
  24. if(typeof name === "function"){
  25. return function(elem){ return isTag(elem) && name(elem.name); };
  26. } else if(name === "*"){
  27. return isTag;
  28. } else {
  29. return function(elem){ return isTag(elem) && elem.name === name; };
  30. }
  31. },
  32. tag_type: function(type){
  33. if(typeof type === "function"){
  34. return function(elem){ return type(elem.type); };
  35. } else {
  36. return function(elem){ return elem.type === type; };
  37. }
  38. },
  39. tag_contains: function(data){
  40. if(typeof data === "function"){
  41. return function(elem){ return !isTag(elem) && data(elem.data); };
  42. } else {
  43. return function(elem){ return !isTag(elem) && elem.data === data; };
  44. }
  45. }
  46. };
  47. function getAttribCheck(attrib, value){
  48. if(typeof value === "function"){
  49. return function(elem){ return elem.attribs && value(elem.attribs[attrib]); };
  50. } else {
  51. return function(elem){ return elem.attribs && elem.attribs[attrib] === value; };
  52. }
  53. }
  54. function combineFuncs(a, b){
  55. return function(elem){
  56. return a(elem) || b(elem);
  57. };
  58. }
  59. exports.getElements = function(options, element, recurse, limit){
  60. var funcs = Object.keys(options).map(function(key){
  61. var value = options[key];
  62. return key in Checks ? Checks[key](value) : getAttribCheck(key, value);
  63. });
  64. return funcs.length === 0 ? [] : this.filter(
  65. funcs.reduce(combineFuncs),
  66. element, recurse, limit
  67. );
  68. };
  69. exports.getElementById = function(id, element, recurse){
  70. if(!Array.isArray(element)) element = [element];
  71. return this.findOne(getAttribCheck("id", id), element, recurse !== false);
  72. };
  73. exports.getElementsByTagName = function(name, element, recurse, limit){
  74. return this.filter(Checks.tag_name(name), element, recurse, limit);
  75. };
  76. exports.getElementsByTagType = function(type, element, recurse, limit){
  77. return this.filter(Checks.tag_type(type), element, recurse, limit);
  78. };