Table of Contents
Create a framework for the library
A brief discussion of concepts
Return to encoding
Using text and HTML
Operation Class
Use Properties
Create elements
Attached and prefixed elements
Delete elements
Usage Events
Usage library
That's it!
Home Web Front-end JS Tutorial Build Your First JavaScript Library

Build Your First JavaScript Library

Mar 11, 2025 am 12:09 AM

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) {

    }
}
Copy after login

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];
};
Copy after login
  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;
        });
    }
}
Copy after login

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);
        }
    });
}
Copy after login

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);
        });
    }
}
Copy after login

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) {

}
Copy after login

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;
}
Copy after login

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);
Copy after login

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) {

}
Copy after login

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);
    });
}
Copy after login

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);
    });
}
Copy after login

  1. Usage library

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

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

From there, you can use it like this:

 new Dome("li")
...
Copy after login

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 of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 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.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 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.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

See all articles