Essential Code for DOM Manipulation

Before starting reading this article you can go over the following articles, if you like:

Well, I’m planning on making a video tutorial series about DOM Manipulation. Here is an outline of it . And this anSRThemeAction is the YouTube channel where you can find that series. If you want me to make the videos, then please subscribe the channel, leave comments letting me know how you’re eagerly waiting for the series. After all your eagerness is my inspiration.

Let me assume that you’ve already read/learn about DOM and DOM Manipulation.
So now, without further ado, let me get straight to our today’s topic.
In this article I’m going to populate some essential and frequently used code which you might often come across. But admittedly, you can also find the code around the web. I just tried to gather and categorize them in one place. My heart-felt gratitude goes to w3schools.com because I made this tutorial, generally, based on w3schools.com.
So, I categorize the entire DOM Manipulation code into three categories. They are –


1.   HTML DOM
2.   HTML DOM Nodes
3.   HTML DOM Events

As I said in this ‘DOM Manipulation – in a nutshell’ article, each of the categories has some common operations like GET, SET, ADD, DELETE, CREATE etc. Now it’s time to go through every category, and of course, read carefully side notes to know the specific code’s role. You can use w3schools.com to see examples. 

               HTML DOM
ACCESS/CATCH/GRAB/FETCH/GET/FIND HTML elements

1. by HTML Object Collections


document // to select/grab the html document itself
document.documentElement // to select/grab the <html> element
document.body // to select/grab the <body> element document.body.scrollTop > 50
document.head
document.title
document.scripts
document.anchors
document.links
document.forms
document.images
document.forms['frm1'// This code finds the form element with id='frm1', in the forms collection
document.forms['frm1'].elements[0].value // grab the value of the first input element of the form with id='frm1'


2. by ID, CLASS and TAG name


document.getElementById('name'// get an element by its id name
document.getElementsByClassName('listItem'// get all elements with the class name of listItem 
document.getElementsByClassName('listItem')[0// get the first element with the class name of listItem 
document.getElementsByTagName('li'// get all <li> elements
document.getElementsByTagName('li')[0// get the first <li> element


3. by CSS SELECTORS


document.querySelector('.listItem'// get the first element with the class name of listItem
document.querySelector('#listId'// get an element by its id name
document.querySelector('form'// get the element by its tag name. It grabs the first <form> in the document
document.querySelector('form')['inputId'// get an element with the id="inputId" (also for name="inputId") which is a child of the <form>. This approach is working only for <form> as far as I tested
document.querySelector('form').inputId // alternate code of the above approach. The difference is here 'inputId' is the id='inputId' of the <input>. It doesn't work for name="". This approach is working only for <form> as far as I tested
document.querySelector('form.userInput.login input[name="email"]'// example from MDN. Grabing the <input type='email' name='email'/>

// document.querySelector('.para1, .para2')// get more than one element by their class names. It's not working when I tested 

document.querySelectorAll('.listItem'// get all elements with the class name of listItem 
document.querySelectorAll('.listIteme')[0// get the first element with the class name of listItem 


Set/Change/Replace HTML elements

Changing HTML elements, text nodes etc


document.querySelector('ul').innerHTML // access the inner HTML element of the selected <ul> element
document.querySelector('ul').innerHTML = '<li><a>ChangeItem innerHTML</a></li>' // change/replace the inner HTML element of the <ul>. It'll remove all other existing elements.
document.querySelector('ul').innerText // access the text content/node (visible only)of the <ul> element
document.querySelector('ul').innerText = 'ChangeItem innerText' // change the text content (only)
document.qeurySelector('ul').textContent // access the text content/node (visible and invisible) of the ul element
document.querySelector('ul').textContent = 'ChangeItem textContent' // change the text content only. the same as the innerText


Changing the value of attributes like src, href etc


document.querySelector('a').href // get the href attribute value of an <a> element 
document.querySelector('a').href = 'www.google.com' // change the href attribute value of an <a> element
document.querySelector('img').src // get the src attribute value of <img>
document.querySelector('img').src = 'www.unsplash.com' // set/change the src attribute value of <img>


Creating/Adding, Changing/Replacing, Accessing/Finding and Removing ATTRIBUTES and attribute VALUES


document.querySelector('#changeStyle').setAttribute('class''changeStyleClass'// creating new attribute and attribute value

document.querySelector('#changeStyle').setAttribute('class''changeStyleClassChanged'// changing/replacing the existing attribute value

document.querySelector('#changeStyle').getAttribute('class'// accessing/finding an attribute value

document.querySelector('#changeStyle').removeAttribute('class'// removing an attribute and attribute value

document.querySelector('#changeStyle').attributes // finding the number of attributes the specified element has
document.querySelector('#changeStyle').attributes[0// finding the first attribute's name and value
document.querySelector('#changeStyle').attributes[0].name // finding the first attribute's name
document.querySelector('#changeStyle').attributes[0].value // finding the first attribute's value


Changing the value of CSS property like color, backgroundColor, padding etc


document.querySelector('h2').style.color = 'coral'
document.querySelector('h2').style.backgroundColor = 'black'
document.querySelector('h2').style.padding = '10px'
document.querySelector('h2').style.fontSize = '10px'


Adding, Removing/Deleting, Switching CSS class name


document.querySelector('#changeStyle').classList.add('jumbotron''jumbotron1')// add class="jumbotron jumbotron1"
document.querySelector('#changeStyle').classList.remove('jumbotron','jumbotron1')// remove class name class="jumbotron jumbotron1"
document.querySelector('#changeStyle').classList.toggle('jumbotron'// switching between  class names 

// example
document.querySelector('#addClassName').addEventListener('click', () => {
    document.querySelector('#addClassName').classList.toggle('myStyle')
})

document.querySelector('#changeStyle').classList.replace("changeList""reChangeList"); // replace class name "changeList" with "reChangeList"
document.querySelector('#changeList').classList.length // returns the number of class name in the list
document.querySelector('#changeList').classList.contains('changeList'// returns a boolean value, indicating whether an element has the specified class name

document.querySelector('#changeStyle').className = 'display-4 py-5' // it will remove the existing class name and add these two 'display-4 py-5' class names. That means this will replace the old class names with the given ones. It works almost the same as the classList.replace(). The difference is that in this case we don't need to know/mention the name of the old ones.
document.querySelector('#changeStyle').className += " anotherClassName" // it will add a new class name (anotherClassName) with the old ones.



             HTML DOM Nodes

nodeName


// nodeName of an element node is the same as the tag name
document.querySelector('h1').nodeName
//nodeNmae of an attribute node is the attribute name
// nodeName of a text node is always #text
document.querySelector('h1').firstChild.nodeName
// nodeName of the document node is always #document
document.nodeName


nodeValue


// nodeValue for element nodes is null 
document.querySelector('h1').nodeValue
// nodeValue for text nodes is the text itself
document.querySelector('h1').firstChild.nodeValue
// nodeValue for attribute nodes is the attribute value


nodeType


// nodeType returns the type of a node - 
document.querySelector('h1').nodeType // - 1 - element node
//ELEMENT_NODE - 1 - <h1 class="heading">anSRThemeAction</h1>
// ATTRIBUTE_NODE - 2 - class="heading" (deprecated)
// TEXT_NODE - 3 - anSRThemeAction
// COMMENT_NODE - 8 - <!-- this is a comment -->
// DOCUMENT_NODE - 9 - The HTML document itself (the parent of <html>)
// DOCUMENT_TYPE_NODE - 10 - <!Doctype html>



Finding/Accessing/Grabbing HTML DOM Nodes

Root DOM Nodes


document // to grab the document (parent of the <html> element)itself
document.documentElement // to access to the full document i.e. <html> element
document.body // allows access to the body element


Other DOM Nodes


document.querySelector('.listItem').parentNode
// returns the whole parent element node
<!-- <ul id=​"unorderedList">
        ​<li class=​"listItem" id=​"listId">​List Item One​</li>
        ​<li class=​"listItem">​List Item Two​</li>​ 
        <-- <li class=​"listItem">​List Item Three​</li>
        ​<li class=​"listItem">​List Item Four​</li>
    ​</ul>

document.querySelector('.listItem').parentElement // the same as parentNode

document.querySelector('#unorderedList').childNodes // returns nodeLists of all child nodes, including text nodes, comment nodes etc, of the specified parent node '#unorderedList'. It detects white space as a text node.
document.querySelector('#unorderedList').childNodes[0// returns the first child of the parent.
document.querySelector('#unorderedList').hasChildNodes() // returns boolean value, whether the specified parent element has any child nodes.

document.querySelector('#unorderedList').children // returns a Collection of an element's child elements. It doesn't include white space and detects only element nodes
document.querySelector('#unorderedList').children[0// returns the first child element of the specified parent node.
document.querySelector('#unorderedList').children[0].text // returns the text of the first child element of the specified parent node.
document.querySelector('#unorderedList').children.length // finding out how many children the specified parent node has.

document.querySelector('#unorderedList').firstChild
 // finds the first child node as an element node, a text node or a comment node (depending on which one first) of the specified parent node. Whitespace inside elements is considered as text, and text is considered as nodes.
document.querySelector('#unorderedList').firstChild.textContent // get the text of the first child node
document.querySelector('#unorderedList').firstChild.nodeName // get the node name  of the first child node

document.querySelector('#unorderedList').firstElementChild // finds the first child node as an element node(ignores text and comment nodes).
document.querySelector('#unorderedList').firstElementChild.textContent // finds the text of the first child node.
document.querySelector('#unorderedList').firstElementChild.nodeName // finds the node name (element node only) of the first child (ignores text and comment nodes).

document.querySelector('#unorderedList').lastChild // returns the last child node (as an element node, a text node or a comment nocde depending on which one's last. Whitespace inside elements is considered as text, and text is considered as nodes

document.querySelector('#unorderedList').lastElementChild // returns the last child elements as an element node(ignores text and comment nodes) of the specified element.

document.querySelector('#listId').nextSibling // returs the node immediately following the specified node, in the same tree level. It returns the next sibling node as an element node, a text node or a comment node.

document.querySelector('#listId').nextElementSibling // returns the element immediately following the specified element, in the same tree level. It returns the next sibling node as an element node (ignores text and comment nodes)

document.querySelector('#listId1').previousSibling // returns the previous node of the specified node. It returns the previous sibling node as an element node,  a text node or a comment node.
document.querySelector('#listId1').previousElementSibling // returns the previous element of the specified element, in the same tree level. It returns the previous sibling node as an element node (ignores text and comment nodes)




CREATING new HTML elements (Nodes)


document.createElement('p'// creating a p element
document.createTextNode('this is text which is called TextNode from the developers perspective.'// creates a Text Node with the specified text
document.createAttribute("id"// create a 'id' attribute
document.createAttribute('id').value = 'myId' // set the value 'myId' of the 'id' attribute


ADDING HTML Nodes 


// adding HTML elements/element nodes

document.querySelector('div').appendChild('p'// adding a p element as a last child of a parent element div

// example
let para = document.createElement('p')
let textNode = document.createTextNode('this is Text Node')
para.appendChild(texNode)

document.querySelector('div').insertBefore(insertElement, beforeThisOne) // adding a child element'insertElement'  before the 'beforeThisOne' child element where these two child elements have a parent element 'div'

// example
let insertElement = document.createElement('p')
let textNode = document.createTextNode('this is Text Node')
insertElement.appendChild(texNode)

let div = document.querySelector('#div')
let beforeThisOne = document.querySelector('#p1')
div.insertBefore(insertElement, beforeThisOne)

// adding attributes and values/ attribute nodes

document.querySelector('h1').setAttributeNode() // add an attribute node to an element

// example
let att = document.createAttribute('class'// creating a 'class' attribute
att.value = 'attClassName' // setting the value of the 'class' attribute
document.querySelector('#changeHref').setAttributeNode(att) // adding the 'class' attribute to '#changHref' element


FINDING HTML Nodes


// finding attributes and attributes values 
document.querySelector('#changeHref').getAttributeNode('id'// finding an attribute node and it's value of an element (id="changeHref")
document.querySelector('#changeHref').getAttributeNode('id').value // finding the value of the id attribute. ALTERNATE CODE : document.querySelector('#changeHref').attributes[0].value 


REMOVING / DELETING elements


document.querySelector('p').remove() // removing the p element
document.querySelector('#div').removeChild(document.querySelector('#p')) // you need to grab the parent and the child by their id/class etc.

// removing attributes and values
document.querySelector('h1').removeAttributeNode() // removes the specified attribute form an element

// example
let att = document.querySelector('#changeHref').getAttributeNode('id'// find/get the id attribute node form

document.querySelector('#changeHref').removeAttributeNode(att)


REPLACING  elements


document.querySelector('#div').replaceChild(replaceWithElement,replaceableElement)

// example
let replaceWithElement = document.createElement('p');
let textNode = document.createTextNode('this is text node')
replaceWithElement.appendChild(textNode)

let parent = document.querySelector('#div')
let replaceableElement = document.querySelector('#repP')

parent.replaceChild(replaceWithElement, replaceableElement)



HTML DOM Events

DOM Events can be set in three ways.

1. Using HTML event attribute
2. Using JavaScript
3. Using JavaScript Event Listener

1. Using HTML event attribute


// onclick
 <p id="cpara" class="clickPara" onclick="this.classList.toggle('clickParaclick')" >Hey buddy! Click me and see the magic!</p> 


2. Using JavaScript


// onclick
document.querySelector('#cpara').onclick = () => {
    document.querySelector('.clickPara').classList.toggle('clickParaclick')
}


3. Using JavaScript Event Listener


// click
document.querySelector('#cpara').addEventListener('click', () => {
    document.querySelector('.clickPara').classList.toggle('clickParaclick')
})



Mouse Events


onclick / click // This evnet is triggered when a user clicks on an element
onmousedown / mousedown //This event is trggered when a user presses a mouse button over an element.
onmouseup / mouseup // This event is triggered when a user releases the mouse button over an element.
onmouseover / mouseover // This event is triggered when   the mouse pointer enters an element, or over one of its children. The same as onmouseenter. But this event occurs when the mouse pointer enters the div element, and its child elements (p and span)
onmouseout / mouseout // This event is triggered when a user moves the mouse pointer out of an element, or out of one of its children. The same as onmouseleave. But this event occurs when the mouse pointer is moved out of the div element, and when it learves its child elements (p and span)
onmouseenter / mouseenter //This event ocuurs when the pointer is moved onto (entered) an element. It is similar to the onmouseover event. The only difference is that onmouseenter event does not bubble (does not propagate up the document hierarchy). This event only occurs when the mouse pointer enters the div element.
onmouseleave / mouseleave // This event occurs when the pointer is moved out of an element. It is similar to the onmouseout event. The only difference is that the onmouseleave event does not bubble( does not propagate up the document hierarchy). The onmouseleave event only occurs when the mouse pointer is moved out of the div element.
onmousemove / mousemove // This event occurs when the pointer is moving while it is over an element.



Event Object


onsubmit / submit // This event occurs when a form is submitted.
onchange / change // This event occurs 1. when the content of a form element, the selection, or the checked state have changed ( for input , select, and textarea ). 2. For radiobuttons and checkboxes, the onchange event occurs when the checked state has been changed.
onreset / reset // This event occurs when a form is reset.


Input Events


oninput / input // This event is triggered when a user writes something in an input field. 1. It occurs when an element gets user input. 2. when the vlue of an input or textarea element is changed.


Focus Events


onfocus / focus // This event is triggered when a user clicks on an input field. This event occurs when an element gets focus. This event is most often used with input, select and a. It is similar to the onfocusin event
onblur / blur // This event is triggered when a user leaves an input field. This event occurs when an element loses focus. This event is most often used with form validation code(e.g. when the user leaves a form field). It is similar to the onfocusout event


Keyboard Events


onkeydown / keydown // This event is triggered when a user is pressing a key. 
onkeypress / keypress // This event is triggered when a user presses a key. This event is not fired for all keys (e.g. ALT, CTRL, SHIFT, ESC) in all browsers. To detect only whether the user has pressed a key, use the <strong>onkeydown</strong> event instead, because it works for all keys
onkeyup / keyup // This event is triggered when a user releases a key.


UI Events


onload / load // This event is triggered when a user enters a page; that means when the page loads. 1. Onload is most often used withing the body element to execute a script once a web page has completely loaded all content ( including images, script files, CSS files, etc.) 2. This event can be used to check the visitor's browser type and browser version, and load the proper version of the web page based on the information. 3. It can also be used to deal with cookies.
onunload / unload // This event is triggered when the user leaves the page. This event occurs -- 1. once a page has unloaded(only for body tag), or the browser window has been closed. 2. when the user navigates away from the page (by clicking on a link, submitting a form, closing the browser window, etc.). 3. when a user reloads the page (and the onload event)
onresize / resize // this event occurs when the document view is resized


Comments

  1. Nice articles !!!

    Very good stuff

    All are best with description

    Deep learning

    ReplyDelete
  2. Thank you so much, myblog.
    Stay tunned!

    ReplyDelete
  3. Bola168 Betting - konicasino 코인카지노 코인카지노 카지노 카지노 sbobet ทางเข้า sbobet ทางเข้า 34Best Online Casinos for South Korea 2020 | Won by Experts

    ReplyDelete

Post a Comment

Popular Posts