Web Developer| Biochemist|Language Lerner|Music

Web Developer| Biochemist|Language Lerner|Music

Interesting ways to manipulate the DOM using (vanilla) JavaScript (Part 1)

Interesting ways to manipulate the DOM using (vanilla) JavaScript (Part 1)

Part 2 is up!

So I am at the moment reading the book “DOM Enlightment“, a really good book, and I thought to myself  “Hmm.. why dont you blog about what you are learning form this book?”. So yea, hope you can get something out of this.

Remember this, HTML is a tree  made up of node objects (think of them as leaves or branches, however you want), the DOM (Document Object Model). Every element you see in an HTML is a Node with a specific type e.g. ElementNode or an instance of an interface (I guess it inherits properties provided by that interface)

Node Types

  1. DOCUMENT_NODE e.g. window.document
  2. ELEMENT_NODE e.g. body, a, p, script tags etc.
  3. ATTRIBUTE_NODE e.g. class, id, data
  4. TEXT_NODE e.g. text content/characters including white spaces
  5. DOCUMENT_FRAGMENT_NODE e.g. document.createDocumentFragment()
  6. DOCUMENT_TYPE_NODE e.g. !DOCTYPE html

Each Node type inherits from the Node Object. View the properties below listed after console.dir() a selected h1 element.

 

Okay let us begin with the reason why you are reading this. Again if you want to know more about the DOM, Node, types, do purchase the book.

These nodes apparently represent numbers, but personally I do not see the need to  learn or know them. Thus we are going to skip that part. However, if you are interested to know, do purchase the book.

Below are listed a few methods you can use when adding dynamics to your web site, I also included codepen examples for better comprehension.

 

Creating and Updating Elements or/and Text elements

  1. document.createElement()
    1. creates a new element Node e.g. h1, div
  2. document.getElementById(“message”).innerHTML =” <p>my name is Comfort</p>”
    1. this selects an element with the id attribute set to “message”, then sets /updates the selected node’s innerHTML to a node element p (with the text node – my name is Comfort)
      1. you can replace  innerHTML (replaces the content of element with id “message” if “=” used; else if +=, “adds to the content) with  the following properties
        1. outerHTML (replaces the element with id “message”)
        2. textContent (similar to innerHTML, however updates the content of element with id=”message” with a text node)
        3. innerText (same with textContent but replaces the selected element itself)
        4. outerText (similar to innerText)
Note: You can use these methods to "GET" / "READ" the data embedded in the selected element. Either by directly console.log(selected.innerHTML) or storing it in a variable and then console-ing the variable.

 

See the Pen DOM Manipulation: creating and updating elements by Ajala Comfort (@AJALACOMFORT) on CodePen.

 

Inserting Elements

  1. insertAdjacentHTML method
    1. this method accepts two arguments, the position where the elements is to be inserted, and the element to be inserted.
  2. appendChild
    1. appends a node (method argument) or multiple to the end of the selected node
  3. insertBefore
    1. if you want more control in terms of insertion position, use this method.

 

See the Pen DOM Manipulation: Inserting Elements to the DOM by Ajala Comfort (@AJALACOMFORT) on CodePen.

Removing and Replacing Nodes

to remove / replace; select node to be removed –> point to the parentNode of the selection –> access removeChild method of the parentNode –> pass selection as an argument to the method

removeChild

replaceChild –> unlike removeChild, takes two arguments (the element to be replaced by, the element to be replaced)

See the Pen DOM Manipulation: Removing and Replacing Nodes by Ajala Comfort (@AJALACOMFORT) on CodePen.

I need to rest, but I will update the list soon

23/08/2017 – UPDATE

I am back.. okay.

Another method, which I found interesting is for cloning nodes

  1. CloneNode
    1. to duplicate a node  alone or a node and its child nodes.
    2. this takes in only one argument, a boolean.
      1. By default the boolean is false (to clone only the node), but you can set it to true to clone a node and its child nodes
      2. Note: when cloning a node, you are inheriting all its attributes  and their values  and inline events e.g. onclick=”alert(‘I love Comfort’s Blog’)”. This may lead to duplicated ids.

 

See the Pen DOM Manipulation: Cloning Nodes by Ajala Comfort (@AJALACOMFORT) on CodePen.

 

Working with Node List – Collection of nodes

Getting A list of immediate/direct children (Child Nodes) – not a method, but a property

childNodes, similar to firstNode but returns the direct children of the node selected. You are more likely to use this to determine how many li are in a selected ul (for example) that to manipulate something.

Changing the gotten Node List into an array (javaScript array)

use the Array prototype methode slice and call it on the node list. This returns a true JavaScript array

 

 

 

See the Pen DOM Manipulation: Working with Node Lists by Ajala Comfort (@AJALACOMFORT) on CodePen.

 

Traversing the DOM

to transverse (go up or down) the DOM, you could use the follow properties. You may have encountered their usage a few lines ago.

  1. parentNode
  2. firstChild
  3. lastChild
  4. nextSibling
  5. previousSibling
  6. firstElementChild
  7. lastElementChild,
  8. nextElementChild,
  9. previousElementChild,
  10. children
  11. parentElement
  12. childElementCount – returns the number of element nodes of a node selection

Warning: To save you from frustration, also put in mind that even a space/tab is considered a firstChild. So if you attempted on selecting the first child of a node and it does not return the expected element/node, check if their is a space, or tab after the parent that is being selected. However to directly skip text node while targeting an element node,  use the firstElementChild instead.

let’s look at their application

See the Pen QMxGwV by Ajala Comfort (@AJALACOMFORT) on CodePen.

I will be back!

and back…. few  hours later. So where were we?

setting and getting attributes and properties

  1. setAttribute, getAttribute, hasAttribute, removeAttribute
    1. set – updates the attribute with the argument provided (second argument)
    2. get – returns the attribute value
    3. has – returns a boolean; if the selected node has a given attribute
    4. remove – removes the attributes value
  2. classList, className
    1. className returns a list of class e.g. <p class=”name bean red”>whatever</p> returns “name bean red”
    2. while classList returns an object, which looks like  in the image below.
  3. data* manipulation
    1. setting and getting actions are performed using the dataset property

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

See the Pen DOM Manipulation: Setting, Getting, Removing, Checking Attributes by Ajala Comfort (@AJALACOMFORT) on CodePen.

Selection

  1. querySelector
    1. returns the first node in the DOM based on the selector
  2. getElementById
    1. returns a node based on the attribute id
  3. querySelectorAll
    1. returns a static list (not live) of all the nodes based on the selector
  4. getElementsByTagName
    1. returns a live list of all nodes based on the selector
  5. getElementsByClassName
    1. similar to (4) but selection based on class
  6. document.all
    1. selects all elements in the HTML document
  7. document.forms
    1. selects all <form> elements in the document
  8. document.images
    1. selects all <img> elements in the document
  9. document.scripts
    1. selects all <script> elements in the document
  10. document.styleSheets
    1. selects all <link>  or <style> elements in the document

We don’t need codepen examples, do we ?

I find the method scrollIntoView very useful, especially when creating a single page portfolio for instance.  To scroll to the bottom of the element to be scrolled to (hope that made sense :D), add false as an argument of the method. Else the default, true, will scroll to the top of the element.

 

 

See the Pen DOM Manipulation: ScrollIntoView method by Ajala Comfort (@AJALACOMFORT) on CodePen.

 

Look forward to part 2



shares