avoid-removeChild.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /**
  2. * @fileoverview Reject using element.parentNode.removeChild(element) when
  3. * element.remove() can be used instead.
  4. *
  5. * This Source Code Form is subject to the terms of the Mozilla Public
  6. * License, v. 2.0. If a copy of the MPL was not distributed with this
  7. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  8. */
  9. "use strict";
  10. var helpers = require("../helpers");
  11. module.exports = {
  12. meta: {
  13. docs: {
  14. url:
  15. "https://firefox-source-docs.mozilla.org/code-quality/lint/linters/eslint-plugin-mozilla/avoid-removeChild.html",
  16. },
  17. type: "suggestion",
  18. },
  19. create(context) {
  20. return {
  21. CallExpression(node) {
  22. let callee = node.callee;
  23. if (
  24. callee.type !== "MemberExpression" ||
  25. callee.property.type !== "Identifier" ||
  26. callee.property.name != "removeChild" ||
  27. node.arguments.length != 1
  28. ) {
  29. return;
  30. }
  31. if (
  32. callee.object.type == "MemberExpression" &&
  33. callee.object.property.type == "Identifier" &&
  34. callee.object.property.name == "parentNode" &&
  35. helpers.getASTSource(callee.object.object, context) ==
  36. helpers.getASTSource(node.arguments[0])
  37. ) {
  38. context.report(
  39. node,
  40. "use element.remove() instead of " +
  41. "element.parentNode.removeChild(element)"
  42. );
  43. }
  44. if (
  45. node.arguments[0].type == "MemberExpression" &&
  46. node.arguments[0].property.type == "Identifier" &&
  47. node.arguments[0].property.name == "firstChild" &&
  48. helpers.getASTSource(callee.object, context) ==
  49. helpers.getASTSource(node.arguments[0].object)
  50. ) {
  51. context.report(
  52. node,
  53. "use element.firstChild.remove() instead of " +
  54. "element.removeChild(element.firstChild)"
  55. );
  56. }
  57. },
  58. };
  59. },
  60. };