Vanilla JavaScript in the browser now has many of the features of jQuery built-in.
Therefore, we don’t need to use jQuery to do many things.
In this article, we’ll look at the vanilla JavaScript equivalent of jQuery features.
Creating Elements
We can use jQuery’s $
function to create elements.
For instance, we can write:
$("<div/>");
$("<span/>");
to create a div and span respectively.
To do the same thing with vanilla JavaScript, we use the document.createElement
method:
document.createElement("div");
document.createElement("span");
To add some content to the created elements, we can set the textContent
property to add text.
Or we can attach child nodes with the appendChild
method.
To add text content, we write:
const element = document.createElement("div");
element.textContent = "text"
And to add child node, we can write:
const element = document.createElement("div");
const text = document.createTextNode("text");
element.appendChild(text);
Updating the DOM
In jQuery, we can use the text
method to update the text content of an element.
For instance, we can write:
$("div").text("New text");
And to return the text content of the selected element, we can write:
$("div").text();
to call text
with no argument.
To set the text content of an element with vanilla JavaScript, we can write:
document.querySelector("div").textContent = "New text";
And to get the text content of the selected element, we write:
document.querySelector("div").textContent
In jQuery to append a new child element, we use the append
method:
$(".search-result").append($("<div/>"));
We append a new div to the element with class search-result
.
To do the same thing with vanilla JavaScript, we call appendChild
:
const element = document.createElement("div");
document.querySelector(".search-result").appendChild(element);
We create the div with createElement
and pass the returned element into appendChild
.
Conclusion
We can create text nodes and elements and attach it easily into the DOM with vanilla JavaScript.