首页 > web前端 > js教程 > 正文

使用 Vanilla JavaScript 实用函数简化 DOM 操作

WBOY
发布: 2024-09-06 21:00:40
原创
982 人浏览过

Simplifying DOM Manipulation with a Vanilla JavaScript Utility Function

介绍

如果您曾经使用过 jQuery,您就会知道它对于选择和操作 DOM 元素有多么方便。但是,如果您希望在普通 JavaScript 中实现类似的功能,而不需要引入整个 jQuery 库,该怎么办?在本文中,我们将介绍如何创建一个简化的实用函数,该函数模仿 jQuery 的一些核心功能,例如选择元素和添加类,所有这些都使用纯 JavaScript。

让我们分解一个简洁的实用函数,它能够以干净、可链接的方式进行 DOM 操作。我们将逐步构建它并解释每个部分。

守则

const $ = function (selector = null) {
    return new class {
        constructor(selector) {
            if (selector) {
                // Check if selector is a single DOM element (nodeType present)
                if (selector.nodeType) {
                    this.nodes = [selector];  // Convert the element into an array
                } 
                // Check if selector is a NodeList
                else if (NodeList.prototype.isPrototypeOf(selector)) {
                    this.nodes = selector;  // Use the NodeList as-is
                } 
                // Otherwise assume it's a CSS selector string
                else {
                    this.nodes = document.querySelectorAll(selector);
                }
                // Store the first element in the variable 'n'
                this.n = this.nodes[0];
            }
        }

        each(callback) {
            this.nodes.forEach(node => callback(node));
            return this;  // Return 'this' for method chaining
        }

        addClass(classNames) {
            return this.each(node => {
                const classes = classNames.split(",").map(className => className.trim());  // Split and trim classes
                node.classList.add(...classes);  // Add the classes to the element
            });
        }
    }(selector);
}
登录后复制

解释

  1. 创建 $ 函数
   const $ = function (selector = null) {
登录后复制

$ 函数是一个模仿 jQuery 的 $ 选择器的简化实用程序。它接受选择器作为参数,该参数可以是 CSS 选择器字符串、单个 DOM 元素或 NodeList。

  1. 匿名类和构造函数
   return new class {
       constructor(selector) {
           if (selector) {
登录后复制

该函数返回匿名类的实例。在构造函数内部,它检查选择器的参数类型并进行相应处理。

  1. 处理选择器
   if (selector.nodeType) {
       this.nodes = [selector];  // Convert the element into an array
   } else if (NodeList.prototype.isPrototypeOf(selector)) {
       this.nodes = selector;  // Use the NodeList as-is
   } else {
       this.nodes = document.querySelectorAll(selector);  // Handle CSS selector strings
   }
   this.n = this.nodes[0];  // Store the first element
登录后复制
  • 如果选择器是 DOM 元素(它具有 nodeType),则将其包装在数组中以实现一致处理。
  • 如果selector已经是一个NodeList,我们直接使用它。
  • 如果它是一个字符串,我们假设它是一个 CSS 选择器,并使用 querySelectorAll 来选择匹配的 DOM 元素。

确定类型后,将第一个选定的元素存储在 this.n 中,以便快速访问。

  1. 每个方法
   each(callback) {
       this.nodes.forEach(node => callback(node));
       return this;  // Allows method chaining
   }
登录后复制

each 方法迭代 this.nodes 中选定的元素,并将提供的回调函数应用于每个元素。它返回此值,以便您可以将多个方法链接在一起。

  1. addClass 方法
   addClass(classNames) {
       return this.each(node => {
           const classes = classNames.split(",").map(className => className.trim());  // Split and trim class names
           node.classList.add(...classes);  // Add the classes to each element
       });
   }
登录后复制

addClass 方法允许您向所选元素添加一个或多个类。它采用以逗号分隔的类名字符串,将它们分开,修剪任何多余的空格,并使用 classList.add 将每个类应用到元素。

使用示例

使用此实用程序,您现在可以以简单、可读的方式操作 DOM,类似于使用 jQuery:

// Select all elements with the class 'my-element' and add 'new-class' to them
$('.my-element').addClass('new-class');

// You can also chain methods, for example, adding multiple classes
$('.my-element').addClass('class-one, class-two');
登录后复制

结论

这个实用函数将 jQuery 的优雅带入了原生 JavaScript 的世界,使 DOM 操作更加直观和可读,而无需依赖外部库。它也是轻量级的,可以根据需要使用更多方法轻松扩展。虽然它不像 jQuery 那样强大或全面,但它以干净、可重用的方式涵盖了许多日常任务。

请随意使用更多方法(如removeClass、toggleClass,甚至css)来扩展此实用程序。这样,您将拥有根据您的特定需求量身定制的迷你框架。


如果您发现这有帮助或有改进建议,请在下面发表评论。让我们一起简化 DOM 操作过程!

以上是使用 Vanilla JavaScript 实用函数简化 DOM 操作的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!