search
HomeWeb Front-endJS TutorialBuild Your First JavaScript Library

Build Your First JavaScript Library

Have you ever been amazed at the magic of React? Ever wondered how Dojo works? Have you ever been curious about jQuery's clever operation? In this tutorial, we will sneak behind the scenes and try to build a super-simplified version of jQuery.

We use JavaScript libraries almost every day. Whether it is implementing algorithms, providing API abstractions, or manipulating DOMs, libraries perform many functions on most modern websites.

In this tutorial, we will try to build a library like this from scratch (this is a simplified version of course). We will create a library for DOM operations, similar to jQuery. Yes, it's fun, but before you get excited, let me clarify a few points:

  • This won't be a fully functional library. We're going to write a solid set of methods, but this is not a complete jQuery. We will do enough to give you a good understanding of the types of problems you will encounter when building libraries.
  • We are not pursuing full compatibility across all browsers here. The code we wrote today should run on Chrome, Firefox, and Safari, but may not work on older browsers such as IE.
  • We will not cover every possible purpose of our library. For example, our prepend methods are only valid when you pass them our library instances; they do not work with original DOM nodes or node lists.

  1. Create a framework for the library

We will start with the module itself. We will use the ECMAScript module (ESM), a modern way to import and export code on the web.

 export class Dome {
    constructor(selector) {

    }
}

As you can see, we export a class called Dome whose constructor will accept a parameter, but it can be of multiple types. If it is a string, we will assume it is a CSS selector, but we can also accept the results of a single DOM node or document.querySelectorAll to simplify element search. If it has a length property, we will know that we have a list of nodes. We will store these elements in this.elements , Dome object can wrap multiple DOM elements, we need to loop through each element in almost every method, so these utilities will be very convenient.

Let's start with a map function that takes a parameter, a callback function. We will loop through the items in the array and collect the content returned by the callback function. Dome instance will receive two parameters: the current element and the index number.

We also need a forEach method, by default we can simply forward the call to mapOne . It's easy to see what this function does, but the real question is, why do we need it? This takes a little bit of what you might call the "library concept".

A brief discussion of concepts

If building a library is just writing code, it wouldn't be too difficult to do. But when working on this project, the harder part I found was deciding how certain methods should work.

Soon we will build a Dome object that wraps multiple DOM nodes ( $("li").text() ) and you will get a single string containing all the element texts concatenated together. Is this useful? I don't think so, but I don't know what a better return value is.

For this project, I will return the text of multiple elements as an array unless there is only one item in the array; then we will return only the text string, not the array containing a single item. I think you get text for a single element the most often, so we optimized for this situation. However, if you are getting text for multiple elements, we will return what you can use.

Return to encoding

So mapOne will first call map and then return a single item in the array or array. If you're still unsure how this works, stay tuned: You'll see!

 mapOne(callback) {
    const m = this.map(callback);
    return m.length > 1 ? m : m[0];
};
  1. Using text and HTML

Next, let's add the text method to see if we are setting or getting. Note that this is just iterating over the elements and setting their text. If we are getting, we will return the mapOne method of the element: if we are working on multiple elements, this will return an array; otherwise, it will be just a string.

html method is almost the same as the text method, except that it will use innerHTML .

 html(html) {
    if (typeof html !== "undefined") {
        this.forEach(function (el) {
            el.innerHTML = html;
        });
        return this;
    } else {
        return this.mapOne(function (el) {
            return el.innerHTML;
        });
    }
}

Like I said: almost the same.


  1. Operation Class

Next, we want to be able to add and delete classes, so let's write addClass and removeClass methods.

Our addClass method will use classList.add method on each element. When passing a string, only that class is added, and when passing an array we will iterate over the array and add all the classes contained therein.

 addClass(classes) {
    return this.forEach(function (el) {
        if (typeof classes !== "string") {
            for (const elClass of classes) {
                el.classList.add(elClass);
            }
        } else {
            el.classList.add(classes);
        }
    });
}

Very simple, right?

Now, what about deleting the class? For this you almost do the same thing, just use classList.remove method.

  1. Use Properties

Next, let's add the attr function. This will be easy as it's almost the same as our html method. Like these methods, we will be able to get and set properties at the same time: we will accept one property name and value to set, and only one property name to get.

 attr(attr, val) {
    if (typeof val !== "undefined") {
        return this.forEach(function (el) {
            el.setAttribute(attr, val);
        });
    } else {
        return this.mapOne(function (el) {
            return el.getAttribute(attr);
        });
    }
}

If val is defined, we will use the setAttribute method. Otherwise, we will use getAttribute method.

  1. Create elements

We should be able to create new elements, and any good library can do that. Of course, this is meaningless as a method of Dome class.

 export function create(tagName,attrs) {

}

As you can see, we will accept two parameters: the name of the element and the attribute object. Most properties will be applied through our attr method, and the text content will be applied to Dome object through text method. Here are the actual actions for all of them:

 export function create(tagName, attrs) {
    let el = new Dome([document.createElement(tagName)]);
    if (attrs) {
        for (let key in attrs) {
            if (attrs.hasOwnProperty(key)) {
                el.attr(key, attrs[key]);
            }
        }
    }
    return el;
}

As you can see, we create the element and send it directly to the new Dome object.

But now we are creating new elements, we will want to insert them into the DOM, right?

  1. Attached and prefixed elements

Next, we will write append and prepend methods. These functions are a bit tricky, mainly because there are multiple use cases. Here are the things we want to be able to do:

 dome1.append(dome2);
dome1.prepend(dome2);

We may want to attach or prefix:

  • A new element to one or more existing elements
  • Multiple new elements to one or more existing elements
  • An existing element to one or more existing elements
  • Multiple existing elements to one or more existing elements

I use "new" to represent elements that are not yet in the DOM; existing elements are already in the DOM. Let's explain it step by step now:

 append(els) {

}

We expect els to be a Dome object. A complete DOM library will accept it as a node or a list of nodes, but we won't do that. We have to iterate through each of our elements, and then in it, we go through each element we want to attach.

If we are appending, the i from the external Dome object passed in as a parameter will only contain the original (uncloned) nodes. So if we append only a single element to a single element, all the nodes involved will be part of their respective prepend methods.

  1. Delete elements

For completeness, let's add a remove method. This will be very simple because we just need to use the removeChild method. To make things easier, we will use the forEach loop to reverse iterate, I will use the removeChild method to reverse iterate the loop, and Dome object for each element will still work properly; we can use whatever method we want, including appending or prefixing it back to the DOM. Not bad, right?

  1. Usage Events

Last but not least, we will write some event handler functions.

Check out the on method and we'll discuss it:

 on(evt, fn) {
    return this.forEach(function (el) {
        el.addEventListener(evt, fn, false);
    });
}

This is very simple. We just need to iterate over the elements and use addEventListener method. The off function (it unhooked event handler) is almost the same:

 off(evt, fn) {
    return this.forEach(function (el) {
        el.removeEventListener(evt, fn, false);
    });
}

  1. Usage library

To use Dome , just put it in the script and import it.

 import {Dome, create} from "./dome.js"

From there, you can use it like this:

 new Dome("li")
...

Make sure that the script you import it is an ES module.

That's it!

I hope you can try our little library and even extend it a little bit. As I mentioned earlier, I've put it on GitHub. Feel free to fork it, play, and send pull requests.

Let me clarify again: the purpose of this tutorial is not to suggest that you should always write your own library. There is a dedicated team working together to make the large, mature library as good as possible. The purpose here is to give you some insight into what might happen inside the library; I hope you have learned some tips here.

I highly recommend digging around in some of your favorite libraries. You will find that they are not as mysterious as you think, and you may learn a lot. Here are some good starting points:

  • 11 things I've learned from jQuery source code (Paul Irish)
  • Behind the Scenes of jQuery (James Padolsey)
  • React 16: Deep in the API compatibility rewrite of our front-end UI library

This post has been updated with Jacob Jackson's contribution. Jacob is a web developer, tech writer, freelancer and open source contributor.

The above is the detailed content of Build Your First JavaScript Library. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Is Python or JavaScript better?Is Python or JavaScript better?Apr 06, 2025 am 12:14 AM

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

How do I install JavaScript?How do I install JavaScript?Apr 05, 2025 am 12:16 AM

JavaScript does not require installation because it is already built into modern browsers. You just need a text editor and a browser to get started. 1) In the browser environment, run it by embedding the HTML file through tags. 2) In the Node.js environment, after downloading and installing Node.js, run the JavaScript file through the command line.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use