ToolJS: DOM Manipulation Using ToolJS
Tags: javascript, tooljs, node, webdev
Published: 2021-01-18 21:48:56

## ToolJS: DOM Manipulation.

The DOM is an integral part of front-end development. The DOM is being manipulated one way or the other using JavaScript. This can sometimes be a bit tedious, as the in-built JavaScript methods can be a bit too long, take for example **document.getElementBy("myElement")**.

Well ToolJS comes with a DOM module that simplifies manipulation of the DOM, lets check it out.

First of all, make sure ToolJS is included in your work environment either by using the script tag with the [CDN](https://unpkg.com/@redeakaa/tooljs@1.0.1/dist/umd/tooljs.min.js) or by using the ES6 Import syntax to either import only the DOM module or to import the whole library and export the DOM module.

```js
// export all methods from the "DOM" module
var $ = ToolJS.export("DOM");
```

Using ES6 destructing import syntax

```js
import { DOM as $ } from "https://unpkg.com/@redeakaa/tooljs@1.0.1/dist/esm/tooljs.esm.js";
```

> NOTE: if you imported the DOM module from the ESM version of the library using ES6 import syntax, then call all methods on the DOM variable you exported it as

Now that we have the DOM methods in a variable "$", we can start manipulation

### Getting elements from the DOM

Getting elements from the DOM is done by calling the **getEl** method with a valid css selector string as its first parameter.

```js
// The code below gets all elements in the DOM with the class "myElements"
var myElements = $.getEl(".myElements");

// The code below gets the element with id = "myParagraph"
var myParagraph = $.getEl("#myParagraph");
console.log(myParagraph);
// => <p id="myParagraph" class="myElements">This is a p tag</p>
```

If more than one element matches the query, then ToolJS returns an instance of the **ToolJSNodeList** array, else it returns the only element found.

Now let's say you want to limit the scope of your **getEl** query to a particular portion of your DOM(maybe a div). You can archieve this by passing a second parameter to the **getEl** method specifying another valid css selector string that matches an element in the DOM.

```js
// The code below gets all "p" elements in the div with class "my-dom"
var myParagraph = $.getEl("p", ".my-dom");
console.log(myParagraph);
// => <p id="myParagraph" class="myElements">This is a p tag</p>
```

The **getEl** method also accepts an optional third parameter, the **options** parameter, an object which manipulates the element(s) returned by the query. This is usually the last parameter in the methods that accepts it.

```js
var myParagraph = $.getEl("p", ".my-dom", {
  css: "color: red; font-size: 30px", // this option accepts any valid css string
  style: { // this option accepts any valid style object property
    fontFamily: "consolas",
    border: "2px solid red"
  },
  title: "I am a paragraph" // this sets the title of each element
});
```

Pretty cool uh(😎)..

> For a list of all the accepted options see [ToolJS DOM Manipulation Options Object](https://redeakaa.github.io/ToolJS/module-DOM.html#~ToolJSNodeListManipulator)

The **options** parameter accepts a set of pre-defined options (see link above) and also accepts the default properties of an element in pure vanilla js, properties such as "id", "className", "title", "tabIndex" and so on..

### Shorthands

The second parameter in the **.getEl** is optional, which means it can be omitted. This also means that you can pass it the **options** object parameter instead.

```js
// get all h4 elements in the DOM and append to the element with class = "my-dom"
$.getEl("h4", {
  attr: { // this option accepts an object
    set: {
      "data-name": "John Doe",
      "aria-label": "ToolJS"
    },
    remove: ["tabIndex", "title"]
  }
  appendTo: ".my-dom",
});
```

### Creating Elements

The ToolJS DOM module ships with it a method **.createEl** that replicates the **document.createElement()** function, and adds a few more functionalities to it.

#### Creating elements using plain old javascript

```js
// this is plain old js

var myNewElement = document.createElement("div");
myNewElement.innerHTML = "Hello i was created just now";
document.body.appendChild(myNewElement);
```

#### Creating elements using ToolJS

```js
// The code below creates an a div element and manipulate it
var myNewElement = $.createEl("div", {
  innerText: "Hello i was created just now",
  appendTo: "body"
});
```

### Binding Events to Elements

Using plain old js to bind say maybe a click event to an element, you would need to get the element from the DOM, then call the **addEventListener** method on the element. Now imagine wanting to do this for multiple elements, it'll be a pain in the a** 😩

Well ToolJS simplifies this for you, and adds a little flavour to it.

```js
// binding an event to all p elements in the DOM
$.on("p", "click", function(){
  alert("This is a " + this.tagName + " tag");
});
```

The code above is familiar to what you would do using JQuery.

Binding multiple events to an element with the same callback can be done by passing an array of events to the event parameter(the second parameter) or passing it a string of events separating each with a comma.

```js
// binding multiple events to all p elements in the DOM
$.on("p", "click, contextmenu, mouseover", function(){
  alert("This is a " + this.tagName + " tag");
});

// binding multiple events to all p elements in the DOM using array
$.on("p", ["click", "contextmenu", "mouseover"], function(){
  alert("This is a " + this.tagName + " tag");
});
``` 

Pretty Basic.

Now say you want to bind multiple events to an element with each event having a different callback function. This can be achieved by passing an object literal of events and functions pairs to the events parameter, instead of a string or array.

```js
// binding multiple events with multiple callbacks to all p elements in the DOM
$.on("p", {
  click: function(){
    alert("I was triggered on a click event");
  },
  contextmenu: function(){
    alert("I was triggered on a contextmenu event");
  },
  mouseover: function(){
    alert("I was triggered on a mouseover event");
  }
});
```

This same syntax can be used in the manipulation options parameter under the **event** option for any of the ToolJS DOM method that accepts it.

```js
// bind events to the h4 elements referenced using the .getEl method
var h4Tag = $.getEl("h4", {
  innerHTML: "<i>You can click on me</i>",
  event: {
    click: function(){
      alert("I was triggered on a click event");
    },
    contextmenu: function(){
      alert("I was triggered on a contextmenu event");
    },
    mouseover: function(){
      alert("I was triggered on a mouseover event");
    }
  }
});
```


So far, we have covered just a few of the methods that ToolJS DOM module offers for manipulating the DOM. Check out the [DOM Module Documentation](https://redeakaa.github.io/ToolJS/module-DOM.html) for a list of all available methods, how to use them and even examples.

Be sure to bookmark this post, as updates will be made periodically as demands are made.

<p class="codepen" data-height="265" data-theme-id="dark" data-default-tab="js,result" data-user="akaawereniya" data-slug-hash="vYXbezP" style="height: 265px; box-sizing: border-box; display: flex; align-items: center; justify-content: center; border: 2px solid; margin: 1em 0; padding: 1em;" data-pen-title="ToolJS: DOM Manipulation Using ToolJS">
  <span>See the Pen <a href="https://codepen.io/akaawereniya/pen/vYXbezP">
  ToolJS: DOM Manipulation Using ToolJS</a> by Redemption Okoro (<a href="https://codepen.io/akaawereniya">@akaawereniya</a>)
  on <a href="https://codepen.io">CodePen</a>.</span>
</p>
<script async src="https://cpwebassets.codepen.io/assets/embed/ei.js"></script>

### Conclusion

ToolJS DOM Module helps us manipulate the DOM and its elements swiftly and efficiently by extending and utilizing JavaScript's DOM methods and functions.