YDNjQ - DOM Manipulation

YDNjQ - DOM Manipulation

YDNjQ - "You Don't need jQuery” is a series of plain JavaScript snippets that will show you how much you can do without using any library and especially jQuery.

Today we are going to take a look at DOM manipulation DOM manipulation is the basis of everyday Front-End tasks and in this blog post, we are going to have a look at how plain JavaScript can help us.

Creating a DOM element

With jQuery we were used to create DOM elements by passing a string representing our element to the $ function, like this:

$('<div>hello</div>')

In plain JavaScript we can use document.createElement() method, which takes a tagName (div, p, section, etc.) and creates the corresponding HTML element.

Now, let's recreate the following jQuery elements structure

$('<div><span>hello</span></div>')

in plain JavaScript.

First, we need to create the parent div element and the child span element for our text.

const parentDiv = document.createElement('div');
const childSpan = document.createElement('span');

Then we need to add our text, I like using a dedicated DOM method document.createTextNode(), that creates a text node.

const textNode = document.createTextNode('hello');

Now, let's combine them using the Node.appendChild() method, which adds a given node to the end of the list of the specified parent node.

parentDiv.appendChild(childSpan).appendChild(textNode);

And this is our result when we call parentDiv:

<div>
	<span>hello</span>
</div>

Removing a DOM element

So what if we need to remove an element? In jQuery we used to select the element and call the remove() function like this: $('div').remove() In plain JavaScript, we can achieve the same result following a similar, but just a bit more verbose path.

First we select the element we want to remove:

const elToRemove = document.querySelector('div');

If you've missed it, here is a quick introduction to plain JavaScript selectors.

Then we step up off the selected element, using the parentNode method, and then we call the removeChild method and pass it to the previously selected element.

elToRemove.parentNode.removeChild(elToRemove);

Easy!

Cloning a DOM element

Sometimes we just need to clone an entire DOM element, in jQuery we used the handy $.clone() method. In plain JavaScript, we have the cloneNode() method, which takes an optional boolean as an argument, which allows us to clone also child elements.

const elToClone = document.querySelector('div');
const cloneEl = elToClone.cloneNode(true);

Now, because we passed a true to cloneNode method, the cloneEl is an exact deep clone of the whole selected element, including all the attributes and child nodes. If we would decide not to pass true to the method, our cloneEl would be a copy of only the elToClone, without child nodes.

Here you have it, basic DOM manipulation in plain JavaScript.