Implement top ten jQuery functions with native JavaScript

In this article I will convert my most commonly used jQuery functions into native JavaScript.

Sometimes I need to create a simple static HTML or login page and don’t want to introduce any libraries or other dependencies. In this case, I only use normal JavaScript to get the job done. To be honest, it feels really good to know how they work.

Now I will share them with you. Please visit the GitHub page to help you at any time: https://github.com/omarld/jqu…

Before you get started, you first need to know that the title is a jQuery function that you want to convert to native JavaScript. Let’s take a brief look at what it does, then the converted JavaScript code and some additional instructions.

1) $(document).ready(..)

Check if the document is loaded and ready to execute the script.

let isLoaded = false;
let myOnLoadCallBack = function(){
    isLoaded = true;
    //my stuff here
}
document.addEventListener("DOMContentLoaded", myOnLoadCallBack());

document.addEventListener('readystatechange', (event) => {
    if (document.readyState === 'complete' && !isLoaded) {
        myOnLoadCallBack();
    }
);

The DOMContentLoaded event listener is used, which is triggered when the DOM tree is built but no other resources (ie style sheets, images, etc.) have been loaded. If any script tags are found in the HTML document , DOMContentLoaded will also wait for these scripts to load.

If there is a script tag after the style, there will be problems when loading the style. When this happens, if the script needs to modify the style, the style is loaded before the script.

DOMContentLoaded is not supported in IE 8 and below . If you have to support IE 8, you should use document.readyState .

The following are the different states:

  • Loading : Loading document
  • Interactive : the document has been completely read
  • Complete : document has been completely read, all the resources (styles, images) is also loaded

2) $(…).HTML()

Find the value of an existing DOM element, or insert something.

To find existing values, simply reference the innerHTML property.

var content = document.querySelector("section#html div.content p.retrieve").innerHTML;

To insert something, assign innerHTML to new content that can contain HTML tags. Please note: this will replace all existing content.

document.querySelector("section#html div.results p.sample").innerHTML = “<p>Starting a newparagraph</p>”;

3) $(…).Append

Insert some HTML at the end of the existing element.

First, you need to find and get the elements we want to insert new content.

var appendEl = document.querySelector("section#append div.content div.results");

Next create the element you want to insert.

var childEl = document.createElement("div");
childEl.innerHTML = "<p>New <strong>child</strong> Content!</p>"

Finally, insert the element.

//appending
appendEl.appendChild(childEl);

Of course, this takes three steps to complete, but it can be simplified.

First create a new element.

var childEl = document.createElement("div");
childEl.innerHTML = "<p>New <strong>child</strong> Content!</p>"

Next find and insert a new element in a row.

document.querySelector("section#append div.content div.results").appendChild(childEl);

If you want to simplify it further, or find yourself doing a lot of work, you can create a wrapper function to do this.

4) $(…).prepend()

Very similar to the append above , the only difference is that this is inserted at the beginning of the element. So we jump directly to a simplified solution.

Create a new element to insert.

var newDiv = document.createElement("div");
var textNode = document.createTextNode("new content to inserted!");
newDiv.appendChild(textNode);

Find existing elements and insert new ones.

document.querySelector("section#prepend div.content p#existing").insertBefore(newDiv, prependEl.firstChild);

5) $(…).empty()

Empty or clear the DOM element. You might think that you only need to assign the innerHTML property to an empty string. But this is only half done, think about what happens if the target element has a child DOM element? We will do this and it is very simple.

Start by clearing the contents of an existing element.

document.getElementById("empty-content").innerHtml = “”;

Ok, how do you deal with all the internal DOM elements now? Clear the existing content first, then delete all child DOM elements in the loop.

var contentEl = document.getElementById("empty-content");
contentEl.innerHtml = "";
while(contentEl.firstChild){
    contentEl.removeChild(contentEl.firstChild);
}

Iterate through the while loop until there are no children to delete.

6) $(…).Attr(name)

Get the attribute value of an existing DOM element, or set an attribute. The important thing to remember is that not all DOM elements have the same properties. For example, checkboxes and buttons (buttons do not have a checked property).

Start by getting the checked property of the checkbox.

let isChecked = document.querySelector("div#attributes input#my-check-box").getAttribute("checked");

Now let’s see how to set the same attribute.

var el = document.querySelector("div#attributes input#my-check-box");

You can change its state by accessing a JavaScript property.

el.checked = true;

You may have noticed that I refer to the checked key as a JavaScript property. What is the difference between an attribute and a JavaScript attribute? In simple terms, properties are JavaScript’s inheritance keys from element attributes. This means that you can access DOM element attributes as JavaScript object properties.

Here are a few key points about propertie and attribute.

  • Property is the JavaScript inherited value from the attribute (ie .class vs className)
  • An attribute is created from an attribute only when it is a standard property. So if you introduce a custom attribute, it won’t be part of the object property.
  • Depending on the element, the available attributes will be different (ie checkboxes and buttons)

7) $(…).val()

Get the value of the matching DOM element. This is also relatively simple, let’s start by getting the value of an existing element.

In order to make these commands clear, I separated them. Although they can be done in one line.

var contentEl = document.querySelector("#my-input-el");
var lnameValue = contentEl.querySelector("input[name='lname']").value;

The settings are equally simple and can be done in one line.

contentEl.querySelector("input[name='fname']").value = "Some random value";

Similar to setting content with innerHTML , this also overrides all current values ​​of the element.

8, 9) $(…).on() | $(…).off()

To add or remove events from an element, use on() or off() accordingly .

Add event handling:

document.getElementById("my-button").addEventListener("click", function(evt){
    //my custom code here
});

Delete event handling, where you need to perform additional checks on the properties supported by the browser.

var toggleFunction = function(){...}
if (toggleBtn.removeEventListener) { // For all major browsers, except IE 8 and earlier
    toggleBtn.removeEventListener("click", toggleFunction);
} else if (toggleBtn.detachEvent) { // For IE 8 and earlier versions
    toggleBtn.detachEvent("click", toggleFunction)
}

Note the following points when adding or removing event processing.

  • The element must or cannot be attached when the code is instantiated.
  • Function references must be the same when an event listener is deleted.
  • Inline anonymous functions do not work because the references are different.
  • Unlike jQuery, when deleting event processing, you must specify the event to be deleted.

There is a way to remove all event handling without ambiguity, which is to clone the element and replace it. This will also eliminate all additional events for child elements.

Finally delete all elements.

var currEl = document.getElementById("button");
var cloneEl= currEl.cloneNode(true);
currEl.parentNode.replaceChild(cloneEl, currEl);

10) $(…).toggle()

Switching the display on an element can be done in several ways. Each method has a different result. You need to decide what you need to do.

The first method is an element of displayproperty change noneto remove elements from the DOM, and set initialto set it back. The point here is that if you switch the display, it will affect your layout and switch elements.

Here, we directly access elements styleto switch the display image elements on the properties.

if(imgEl.style.display && imgEl.style.display === "none"){
    imgEl.style.display = "initial";
} else {
    imgEl.style.display = "none";
}

The second method is to change the element visibility, which hides the element and preserves the layout.

if(imgEl.style.visibility && imgEl.style.visibility === "hidden"){
    imgEl.style.visibility = "initial";
} else {
    imgEl.style.visibility = "hidden";
};

to sum up

If you’ve been using libraries and JavaScript frameworks all the time, it’s easy to overlook the simplicity of some implementations. But most importantly, you also overlook the basic understanding of some of the core working principles of DOM. A good understanding of DOM can not only help you better design applications, but also solve debugging problems.

These are just some of the functions I use most. Now I will share them with you if you want to write your own functions instead of adding libraries that increase the size of the software in your own programs.

Hope this helps you!

Leave a Comment