{"id":115,"date":"2022-01-27T22:11:20","date_gmt":"2022-01-27T22:11:20","guid":{"rendered":"https:\/\/codevoweb.com\/?p=115"},"modified":"2023-05-06T08:54:13","modified_gmt":"2023-05-06T08:54:13","slug":"important-dom-manipulation-methods-in-javascript","status":"publish","type":"post","link":"https:\/\/codevoweb.com\/important-dom-manipulation-methods-in-javascript\/","title":{"rendered":"17 Most Important DOM Manipulation Methods in JavaScript"},"content":{"rendered":"\n<p>If you are a newbie to JavaScript you may have heard of the DOM (Document Object Model). But what exactly is the DOM?<\/p>\n\n\n\n<p>As a developer, whether you are working on projects with frameworks or building a script from scratch with pure JavaScript, there are some essential DOM Manipulation methods you should be comfortable with.<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"800\" height=\"450\" src=\"https:\/\/codevoweb.com\/wp-content\/uploads\/2022\/01\/Essential-JavaScript-DOM-manipulation-methods.webp\" alt=\"Essential JavaScript DOM manipulation methods\" class=\"wp-image-387\" srcset=\"https:\/\/codevoweb.com\/wp-content\/uploads\/2022\/01\/Essential-JavaScript-DOM-manipulation-methods.webp 800w, https:\/\/codevoweb.com\/wp-content\/uploads\/2022\/01\/Essential-JavaScript-DOM-manipulation-methods-300x169.webp 300w, https:\/\/codevoweb.com\/wp-content\/uploads\/2022\/01\/Essential-JavaScript-DOM-manipulation-methods-768x432.webp 768w, https:\/\/codevoweb.com\/wp-content\/uploads\/2022\/01\/Essential-JavaScript-DOM-manipulation-methods-100x56.webp 100w, https:\/\/codevoweb.com\/wp-content\/uploads\/2022\/01\/Essential-JavaScript-DOM-manipulation-methods-700x394.webp 700w, https:\/\/codevoweb.com\/wp-content\/uploads\/2022\/01\/Essential-JavaScript-DOM-manipulation-methods-600x338.webp 600w\" sizes=\"auto, (max-width: 800px) 100vw, 800px\" \/><\/figure>\n\n\n\n<p>In <a href=\"\/9-javascript-dom-traversal-methods\">Understanding How to Manipulate the DOM<\/a>, we went over how to use built-in methods and properties of Nodes and Elements to manipulate the DOM.<\/p>\n\n\n\n<p>However, frameworks like React Js and Vue Js use virtual DOM to manipulate the Real DOM, whereas Angular Js or Angular also uses incremental DOM to manipulate the Real DOM.<\/p>\n\n\n<style>.kb-table-of-content-nav.kb-table-of-content-id_87fe5a-36 .kb-table-of-content-wrap{padding-top:10px;padding-right:10px;padding-bottom:10px;padding-left:10px;border-top:1px solid #abb8c3;border-right:1px solid #abb8c3;border-bottom:1px solid #abb8c3;border-left:1px solid #abb8c3;}.kb-table-of-content-nav.kb-table-of-content-id_87fe5a-36 .kb-table-of-contents-title-wrap{padding-top:0px;padding-right:0px;padding-bottom:0px;padding-left:0px;}.kb-table-of-content-nav.kb-table-of-content-id_87fe5a-36 .kb-table-of-contents-title-wrap{color:#ffffff;}.kb-table-of-content-nav.kb-table-of-content-id_87fe5a-36 .kb-table-of-contents-title{color:#ffffff;font-weight:regular;font-style:normal;}.kb-table-of-content-nav.kb-table-of-content-id_87fe5a-36 .kb-table-of-content-wrap .kb-table-of-content-list{color:#ffffff;font-weight:regular;font-style:normal;margin-top:10px;margin-right:0px;margin-bottom:0px;margin-left:-15px;}@media all and (max-width: 1024px){.kb-table-of-content-nav.kb-table-of-content-id_87fe5a-36 .kb-table-of-content-wrap{border-top:1px solid #abb8c3;border-right:1px solid #abb8c3;border-bottom:1px solid #abb8c3;border-left:1px solid #abb8c3;}}@media all and (max-width: 767px){.kb-table-of-content-nav.kb-table-of-content-id_87fe5a-36 .kb-table-of-content-wrap{border-top:1px solid #abb8c3;border-right:1px solid #abb8c3;border-bottom:1px solid #abb8c3;border-left:1px solid #abb8c3;}}<\/style>\n\n\n<p>Manipulating the Real DOM is a lot slower than most JavaScript operations. This slowness is made worse since most JavaScript frameworks manipulate the DOM much more than they have to.<\/p>\n\n\n\n<p>To address this problem Angular Js, Vue Js, and React Js popularize something called Virtual DOM and Incremental DOM.<\/p>\n\n\n\n<span id=\"ezoic-pub-video-placeholder-107\"><\/span>\n\n\n\n<p> Manipulating the Virtual DOM or Incremental DOM is much faster since nothing gets drawn on the screen.<\/p>\n\n\n\n<p>In your job or if you are a freelancer, you may have to work on existing scripts rather than new projects. So you may not be allowed to use frameworks, libraries or tools.<\/p>\n\n\n\n<p>Knowing these DOM manipulation methods in JavaScript can be really helpful in your career.<\/p>\n\n\n\n<p>In this article, you are going to learn the essential JavaScript DOM manipulation methods with examples.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"what-is-the-dom\">What is the DOM?<\/h2>\n\n\n\n<p>DOM stands for Document Object Model. It is an application programming interface that allows us to create, add, modify and remove elements from the document.<\/p>\n\n\n\n<p>Every page you see in a browser window can be considered as an object. A Document object represents the HTML document that is displayed in that browser window.<\/p>\n\n\n\n<p>The way a document&#8217;s content is accessed and modified is called the DOM (Document Object Model).<\/p>\n\n\n\n<p>In brief, the DOM defines the logical structure of a document and the way a document can be accessed and manipulated.<\/p>\n\n\n\n<p>Knowing these DOM manipulation methods can take your JavaScript skills to the next level.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"creating-elements-in-the-dom\">Creating Elements in the DOM<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"createelement\">createElement()<\/h3>\n\n\n\n<p>The <strong>createElement()<\/strong> method creates a new HTML element within the DOM. The return value is the newly created element.<\/p>\n\n\n\n<p><strong>Syntax:<\/strong>  <code>document.createElement(tagName[, options])<\/code><\/p>\n\n\n\n<p><strong>tagName:<\/strong>  A string that specifies the type of HTML element to be created. It can be any of the HTML tags you know about.<\/p>\n\n\n\n<p><strong>options:<\/strong> An optional parameter that enables us to set an &#8220;is&#8221; attribute when adding an element.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"basic-example\">Basic Example<\/h4>\n\n\n\n<p>What would it look like to create a paragraph?<\/p>\n\n\n\n<pre class=\"line-numbers language-js\"><code>\n\/* Create a new paragraph element *\/\nlet p = document.createElement('p');\n<\/code><\/pre>\n\n\n\n<p>Create a new div element<\/p>\n\n\n\n<pre class=\"line-numbers language-js\"><code>\n\/* Create a new div element *\/\nlet div = document.createElement('div');\n<\/code><\/pre>\n\n\n\n<p>What we are actually doing is creating a new element and assigning the returned created element to a variable.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"adding-elements-to-the-dom\">Adding Elements to the DOM<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"createtextnode\">createTextNode()<\/h3>\n\n\n\n<p>The <strong>createTextNode()<\/strong> method creates a new text node. This method can be used to escape HTML characters.<\/p>\n\n\n\n<p><strong>Syntax:<\/strong>  <code>let text = document.createTextNode(data);<\/code><\/p>\n\n\n\n<p><strong>text:<\/strong> is a text node<\/p>\n\n\n\n<p><strong>data:<\/strong> a string containing the content to be put in the text node.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"basic-example-1\">Basic Example<\/h4>\n\n\n\n<pre class=\"line-numbers language-js\"><code>\n\/\/ Create a new Text Node\nlet question = document.createTextNode('How many frameworks do you know?');\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"node-textcontent\">Node.textContent<\/h3>\n\n\n\n<p>The <strong>textContent <\/strong>property of a Node can be used to retrieve or write text inside a Node. <\/p>\n\n\n\n<p><strong>textContent<\/strong> gets the content of all elements including <mark class=\"kt-highlight\">&lt;script&gt;<\/mark> and <mark class=\"kt-highlight\">&lt;style&gt;<\/mark>  elements.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"basic-example-2\">Basic Example<\/h4>\n\n\n\n<p>Now let&#8217;s create a div and add a text of <mark class=\"kt-highlight\">Hello World<\/mark>.<\/p>\n\n\n\n<pre class=\"line-numbers language-js\"><code>\n\/* Create a new div Element *\/\nlet div = document.createElement('div');\n\n\/* Add the text Hello World *\/\ndiv.textContent = 'Hello World';\n<\/code><\/pre>\n\n\n\n<p><strong>textContent<\/strong> returns every element in a Node. It can return &#8220;hidden&#8221; elements (elements having display none) since it does not take CSS Styles into account.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"htmlelement-innertext\">HTMLElement.innerText<\/h3>\n\n\n\n<p><strong>HTMLElement.innerText<\/strong> is a property that represents the rendered text content of a node and its descendants.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"basic-example-3\">Basic Example<\/h4>\n\n\n\n<p>Let&#8217;s  create a div and add the text Hello World<\/p>\n\n\n\n<pre class=\"line-numbers language-js\"><code>\n\/* Create a new div Element *\/\nlet div = document.createElement('div');\n\n\/* Add the text Hello World *\/\ndiv.innerText = 'Hello World';\n<\/code><\/pre>\n\n\n\n<p><strong>HTMLElement.innerText<\/strong> returns the text content that is displayed on the screen.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"append\">append()<\/h3>\n\n\n\n<p>The <strong>append()<\/strong> method inserts a set of elements or texts after the last child of the Element.<\/p>\n\n\n\n<p><strong>Syntax:<\/strong>  <code>append(...nodesorDOMStrings)<\/code><\/p>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"basic-examples-2\">Basic Examples<\/h4>\n\n\n\n<p>Create a div and append it to the body<\/p>\n\n\n\n<pre class=\"line-numbers language-js\"><code>\n\/* Get the body *\/\nconst body = document.body;\n\n\/* Create a new div element *\/\nconst div = document.createElement('div');\n\n\/* Append the div *\/\nbody.append(div);\n<\/code><\/pre>\n\n\n\n<p>Create a div then add some text to it and append it to the body<\/p>\n\n\n\n<pre class=\"line-numbers language-js\"><code>\n\/* Get the body *\/\nconst body = document.body;\n\n\/* Create a new div element *\/\nconst div = document.createElement('div');\n\n\/* Add a new text node *\/\ndiv.textContent = 'Am a developer';\n\n\/\/ Append the div\nbody.append(div);\n<\/code><\/pre>\n\n\n\n<p>Create a div and paragraph with texts and append them to the body<\/p>\n\n\n\n<pre class=\"line-numbers language-js\"><code>\n\/* Get the body *\/\nconst body = document.body;\n\n\/* Create a new div and paragraph elements *\/\nconst div = document.createElement('div');\nconst p = document.createElement('p');\n\n\/* Add text to elements *\/\ndiv.textContent = 'Am a developer';\np.textContent = 'Hello World';\n\n\/* Append the div and paragraph to the body *\/\nbody.append(div, p);\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"appendchild\">appendChild()<\/h3>\n\n\n\n<p>The <strong>appendChild()<\/strong> method adds a Node after the last child of a specified parent node.<\/p>\n\n\n\n<p><strong>Syntax: <\/strong> <code>appendChild(aChild);<\/code> <\/p>\n\n\n\n<p><strong>aChild<\/strong> the child to append to the given parent node<\/p>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"basic-examples-1\">Basic Examples<\/h4>\n\n\n\n<p>Create a div, add a Hello World text and append it to the body<\/p>\n\n\n\n<pre class=\"line-numbers language-js\"><code>\n\/* Get the body *\/\nconst body = document.body;\n\n\/* Create a new div *\/\nconst div = document.createElement('div');\n\n\/* Add the text Hello world *\/\ndiv.textContent = 'Hello world';\n\n\/\/ Append the div to the body\nbody.appendChild(div);\n\n<\/code><\/pre>\n\n\n\n<p>Create a heading 1 (h1), add the text Hello World and append it to the body<\/p>\n\n\n\n<pre class=\"line-numbers language-js\"><code>\n\/* Get the body *\/\nconst body = document.body;\n\n\/* Create heading 1 (h1) *\/\nconst h1 = document.createElement('h1');\n\n\/* Add the text Hello world *\/\nh1.textContent = 'Hello world';\n\n\/* Append the h1 to the body *\/\nbody.appendChild(h1);\n<\/code><\/pre>\n\n\n\n<p><strong>appendChild()<\/strong> only accepts one argument of a <strong>Node<\/strong> but not <strong>DOMstring<\/strong> or <strong>text<\/strong>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"innerhtml\">innerHTML<\/h3>\n\n\n\n<p>The Element property <strong>innerHTML<\/strong> retrieves or writes HTML or XML markup contained within the element.<\/p>\n\n\n\n<p><strong>Syntax:<\/strong> <code>const content = element.innerHTML; element.innerHTML = content;<\/code><\/p>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"basic-examples\">Basic Examples<\/h4>\n\n\n\n<p>Suppose that you have the following HTML markup:<\/p>\n\n\n\n<pre class=\"line-numbers language-html\"><code>\n&lt;ul id=\"navList\"&gt;\n&lt;li&gt;&lt;a href=\"\"&gt;Home&lt;\/a&gt;&lt;\/li&gt;\n&lt;li&gt;&lt;a href=\"\"&gt;About&lt;\/a&gt;&lt;\/li&gt;\n&lt;li&gt;&lt;a href=\"\"&gt;Contact&lt;\/a&gt;&lt;\/li&gt;\n&lt;\/ul&gt;\n<\/code><\/pre>\n\n\n\n<p>Let&#8217;s use the <mark class=\"kt-highlight\">innerHTML<\/mark> property to get the content of the <code>&lt;ul&gt;<\/code> element:<\/p>\n\n\n\n<pre class=\"line-numbers language-js\"><code>\n\/* Get the ul by it's id *\/\nconst menu = document.getElementById('navList');\n\n\/* Get the ul content with innerHTML *\/\nconsole.log(menu.innerHTML);\n<\/code><\/pre>\n\n\n\n<p>How it works:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>First select the &lt;ul&gt; element by it&#8217;s id (navList) from the DOM with <code>getElementById()<\/code> method.<\/li>\n\n\n\n<li>Now get the HTML content of the &lt;ul&gt; element with <strong>innerHTML<\/strong> property<\/li>\n<\/ul>\n\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;li&gt;&lt;a href=\"\"&gt;Home&lt;\/a&gt;&lt;\/li&gt;\n&lt;li&gt;&lt;a href=\"\"&gt;About&lt;\/a&gt;&lt;\/li&gt;\n&lt;li&gt;&lt;a href=\"\"&gt;Contact&lt;\/a&gt;&lt;\/li&gt;<\/code><\/pre>\n\n\n\n<p>Suppose we now need our menu to also have a Footer link, then we can append the HTML element for the Footer link to the <strong>&lt;ul&gt;<\/strong> element.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/* Get the ul by it's id *\/\nconst menu = document.getElementById('navList');\n\n\/* Append the HTML for the Footer Link to the ul element *\/\nmenu.innerHTML += `&lt;li&gt;&lt;a href=\"\"&gt;Contact&lt;\/a&gt;&lt;\/li&gt;`;<\/code><\/pre>\n\n\n\n<p><strong>Note:<\/strong> Using innerHTML to insert text into a web page can become an attack vector on the site.<\/p>\n\n\n\n<p>HTML5 specifies that a &lt;script&gt; element inserted with <strong>innerHTML<\/strong> should not execute.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"node-insertbefore\">Node.insertBefore()<\/h3>\n\n\n\n<p>The <strong>insertBefore()<\/strong> method inserts a node as a child of some specified parent node before the referenced node.<\/p>\n\n\n\n<p><strong>Syntax<\/strong> <code>insertBefore(newNode, referenceNode);<\/code><\/p>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"basic-examples-3\">Basic Examples<\/h4>\n\n\n\n<p>Suppose that you have the following HTML markup:<\/p>\n\n\n\n<pre class=\"line-numbers language-html\"><code>\n&lt;!DOCTYPE html&gt;\n&lt;html lang=\"en\"&gt;\n  &lt;head&gt;\n    &lt;meta charset=\"UTF-8\" \/&gt;\n    &lt;meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" \/&gt;\n    &lt;meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" \/&gt;\n    &lt;script src=\".\/test.js\" defer&gt;&lt;\/script&gt;\n    &lt;title&gt;createElement&lt;\/title&gt;\n  &lt;\/head&gt;\n  &lt;body&gt;\n    &lt;div id=\"parentElement\"&gt;\n      &lt;div id=\"childElement\"&gt;Am a div&lt;\/div&gt;\n    &lt;\/div&gt;\n  &lt;\/body&gt;\n&lt;\/html&gt;\n\n<\/code><\/pre>\n\n\n\n<p>Then, let&#8217;s use <strong>insertBefore()<\/strong> to insert a <strong>heading 1 (h1)<\/strong> before the first child of the parent element.<\/p>\n\n\n\n<pre class=\"line-numbers language-js\"><code>\n\/* Get parent div by it's id *\/\nconst parentElement = document.getElementById('parentElement');\n\n\/* Create heading 1 (h1) element *\/\nconst h1 = document.createElement('h1');\n\n\/* Add a text of \"My First JavaScript Project\" to the h1 element *\/\nh1.textContent = 'My First JavaScript Project';\n\n\/* Insert the h1 before the first child of the parentElement *\/\nparentElement.insertBefore(h1, parentElement.firstChild);\n<\/code><\/pre>\n\n\n\n<p>How it works<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Get the parent div with <strong>getElementById()<\/strong> method from the DOM<\/li>\n\n\n\n<li>Then create an h1 element with <strong>createElement()<\/strong> method<\/li>\n\n\n\n<li>Now, insert text into the created <strong>h1<\/strong><\/li>\n\n\n\n<li>Finally, insert the <strong>&lt;h1&gt;<\/strong> before the first child of the parentElement<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"insertadjacenthtml\">insertAdjacentHTML()<\/h3>\n\n\n\n<p>The <strong>insertAdjacentHTML()<\/strong> method of the <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/API\/Element\" target=\"_blank\" rel=\"noreferrer noopener\">Element<\/a> interface parses the specified text as HTML or XML markup and inserts the resulting nodes into the DOM tree at a specified position.<\/p>\n\n\n\n<p><strong>Syntax<\/strong> <code>element.insertAdjacentHTML(position, text);<\/code> <\/p>\n\n\n\n<p><strong>position<\/strong> &#8211; A string representing the position relative to the element.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>'beforebegin'<\/code>:  Before the&nbsp;<code>element<\/code>&nbsp;itself.<\/li>\n\n\n\n<li><code>'afterbegin'<\/code>:  Just inside the&nbsp;<code>element<\/code>,  before its first child.<\/li>\n\n\n\n<li><code>'beforeend'<\/code>:  Just inside the&nbsp;<code>element<\/code>,  after its last child.<\/li>\n\n\n\n<li><code>'afterend'<\/code>:  After the&nbsp;<code>element<\/code>&nbsp;itself.<\/li>\n<\/ul>\n\n\n\n<p>Better visualization<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">&lt;!-- beforebegin --&gt;\n&lt;p&gt;\n  &lt;!-- afterbegin --&gt;\n  foo\n  &lt;!-- beforeend --&gt;\n&lt;\/p&gt;\n&lt;!-- afterend --&gt;<\/pre>\n\n\n\n<p>It is not recommended to use <strong>insertAdjacentHTML()<\/strong> method when inserting plain text, use the&nbsp;<a href=\"https:\/\/docs.w3cub.com\/dom\/node\/textcontent\" target=\"_blank\" rel=\"noopener\"><code>Node.textContent<\/code><\/a>&nbsp;property or the&nbsp;<a href=\"https:\/\/docs.w3cub.com\/dom\/element\/insertadjacenttext\" target=\"_blank\" rel=\"noopener\"><code>Element.insertAdjacentText()<\/code><\/a>&nbsp;method.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"modifying-data-attibutes-in-the-dom\">Modifying Data Attibutes in the DOM<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"getattribute\">getAttribute()<\/h3>\n\n\n\n<p>The <strong>getAttribute()<\/strong> method of the <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/API\/Element\" target=\"_blank\" rel=\"noreferrer noopener\">Element<\/a> interface returns the value of a specified attribute on the element.<\/p>\n\n\n\n<p><strong>Syntax<\/strong> <code>const attribute = element.getAttribute(attributeName);<\/code><\/p>\n\n\n\n<p>Suppose you have this HTML<\/p>\n\n\n\n<pre class=\"line-numbers language-html\"><code>\n&lt;!DOCTYPE html&gt;\n&lt;html lang=\"en\"&gt;\n  &lt;head&gt;\n    &lt;title&gt;Data Attribute&lt;\/title&gt;\n  &lt;\/head&gt;\n  &lt;body&gt;\n    &lt;div id=\"data\"&gt;My first Javascript Project&lt;\/div&gt;\n  &lt;\/body&gt;\n&lt;\/html&gt;\n\n<\/code><\/pre>\n\n\n\n<p>Then let&#8217;s use <strong>getAttribute()<\/strong> to get the value of the attribute id of the <strong>&lt;div&gt;<\/strong>.<\/p>\n\n\n\n<pre class=\"line-numbers language-js\"><code>\n\/\/ in a console\nconst div1 = document.getElementById('data');\n\/\/=&gt; <div id=\"data\">My first Javascript Project<\/div>\n\nconst exampleAttr = div1.getAttribute('id');\n\/\/=&gt; \"data\"\n\nconst title = div1.getAttribute('title');\n\/\/=&gt; null\n\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"setattribute\">setAttribute()<\/h3>\n\n\n\n<p>The <strong>setAttribute()<\/strong> method sets an attribute on a specified element.<\/p>\n\n\n\n<p><strong>Syntax<\/strong> <code>Element.setAttribute(name, value);<\/code><\/p>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"basic-example-4\">Basic Example<\/h4>\n\n\n\n<p>Let&#8217;s use the HTML we used in the <strong>getAttribute()<\/strong> example<\/p>\n\n\n\n<p>Now, we need to set an attribute called <strong>name<\/strong> and give it a value of <strong>john<\/strong><\/p>\n\n\n\n<pre class=\"line-numbers language-js\"><code>\n\/* Get the div element *\/\nconst div1 = document.getElementById('data');\n\n\/* Set the attribute name with a value of john on the div *\/\ndiv1.setAttribute('name', 'john')\n<\/code><\/pre>\n\n\n\n<p>How it works<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>First we get the element we want to set the attribute on from the DOM tree with <strong>getElementById()<\/strong> method<\/li>\n\n\n\n<li>Next, we call the setAttribute() method on the element and pass in two arguments, the first argument is the <strong>name<\/strong> of the attribute and the second is the <strong>value<\/strong> of the attribute.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"element-dataset\">Element.dataset<\/h3>\n\n\n\n<p>The <strong>Element.dataset<\/strong> property provides read and write access to custom data attributes (data-*) on elements.<\/p>\n\n\n\n<p><strong>Syntax<\/strong> <code>const dataAttrMap = element.dataset<\/code><\/p>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"basic-example-5\">Basic Example<\/h4>\n\n\n\n<p>Suppose you have this HTML<\/p>\n\n\n\n<pre class=\"line-numbers language-html\"><code>\n&lt;div id=\"user\"&gt;By his Grace&lt;\/div&gt;\n<\/code><\/pre>\n\n\n\n<p>Let&#8217;s get the <strong>&lt;div&gt;<\/strong> by its id and add two datasets (dataset-id and dataset-name) to it.<\/p>\n\n\n\n<pre class=\"line-numbers language-js\"><code>\n\/* Get the div by its id *\/\nconst user = document.getElementById('user');\n\n\/* Add two datasets (dataset-id and dataset-name) *\/\nuser.dataset.id = '1234';\nuser.dataset.name = 'John Doe';\n<\/code><\/pre>\n\n\n\n<p>How it works<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>First we select the element we want to add the datasets to<\/li>\n\n\n\n<li>We use <code>Element.dataset.property<\/code> to assign the datasets to the element<\/li>\n<\/ul>\n\n\n\n<p> Output HTML<\/p>\n\n\n\n<pre class=\"line-numbers language-html\"><code>\n&lt;div id=\"user\" data-id=\"1234\" data-name=\"John Doe\"&gt;By his Grace&lt;\/div&gt;\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"element-classlist\">Element.classList<\/h3>\n\n\n\n<p><strong>classList<\/strong> is a property of an element that holds the class names of the element currently selected. The classList property also returns an array of the classes on the selected element.<\/p>\n\n\n\n<p>Suppose you have this HTML in the body tag<\/p>\n\n\n\n<pre class=\"line-numbers language-html\"><code>\n&lt;div id=\"navigation\" class=\"navbar active\"&gt;\n      &lt;ul&gt;\n        &lt;a href=\"\"&gt;Home&lt;\/a&gt;\n        &lt;a href=\"\"&gt;About&lt;\/a&gt;\n        &lt;a href=\"\"&gt;Search&lt;\/a&gt;\n      &lt;\/ul&gt;\n    &lt;\/div&gt;\n<\/code><\/pre>\n\n\n\n<p>You can select the navigation div by its id with the getElementById() method, then you can fetch the class names of the element using either <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-red-color\">className<\/mark> or <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-red-color\">classList<\/mark> property.<\/p>\n\n\n\n<p>The <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-red-color\">className<\/mark> property returns the class names as a string whilst the <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-red-color\">classList<\/mark> property returns the class names as an array.<\/p>\n\n\n\n<pre class=\"line-numbers language-js\"><code>\n\/\/ Get the navigation by id\nconst navigation = document.querySelector('#navigation');\n\nconsole.log(navigation.className); \/\/=&gt; \"navbar active\"\nconsole.log(navigation.classList); \/\/=&gt; [\"navbar\" \"active\"]\nconsole.log(navigation.classList[0]); \/\/=&gt; \"navbar\"\nconsole.log(navigation.classList[1]); \/\/=&gt; \"active\"\n<\/code><\/pre>\n\n\n\n<p>The classList property is read-only so if you want to manipulate the HTML element&#8217;s classes, you will need to use the methods that come with the <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-red-color\">classList<\/mark> property.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-red-color\">add()<\/mark><\/li>\n\n\n\n<li><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-red-color\">contains()<\/mark><\/li>\n\n\n\n<li><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-red-color\">remove()<\/mark><\/li>\n\n\n\n<li><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-red-color\">replace()<\/mark><\/li>\n\n\n\n<li><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-red-color\">toggle()<\/mark><\/li>\n<\/ul>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"classlist-add-method\">classList add() method<\/h4>\n\n\n\n<p>The <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-red-color\">classList.add()<\/mark> method allows you to add at least one class name to an element, omitting any that are already present.<\/p>\n\n\n\n<p>Here\u2019s an example of adding a new class name to the navigation &lt;div&gt;&nbsp;element above:<\/p>\n\n\n\n<pre class=\"line-numbers language-js\"><code>\n\/* Get the navigation by id *\/\nconst navigation = document.querySelector('#navigation');\n\n\/* Add a single class to the navigation div *\/\nnavigation.classList.add('open');\n<\/code><\/pre>\n\n\n\n<p>Here\u2019s an example of adding multiple class names to the navigation &lt;div&gt;&nbsp;element above:<\/p>\n\n\n\n<pre class=\"line-numbers language-js\"><code>\n\/* Get the navigation by id *\/\nconst navigation = document.querySelector('#navigation');\n\n\/* Add a single class to the navigation div *\/\nnavigation.classList.add('open', 'close', 'greet', 'salute');\n<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"classlist-contains-method\">classList contains() method<\/h4>\n\n\n\n<p>The <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-red-color\">classList.contains()<\/mark> method check on the element&#8217;s class attribute to see if it contains the specified class name.<\/p>\n\n\n\n<p>It accepts the class name to be checked as an argument. The method will return <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-red-color\">true<\/mark> if the specified class is present or <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-red-color\">false<\/mark> if it&#8217;s not present.<\/p>\n\n\n\n<pre class=\"line-numbers language-js\"><code>\n\/* Get the navigation by id *\/\nconst navigation = document.querySelector('#navigation');\n\n\/* Add a single class to the navigation div *\/\nnavigation.classList.contains('navbar'); \/\/=&gt; true\nnavigation.classList.contains('myBoy'); \/\/=&gt; false\n<\/code><\/pre>\n\n\n\n<p>In brief, the <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-red-color\">contains()<\/mark> method return a boolean.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"classlist-remove-method\">classList remove() method<\/h4>\n\n\n\n<p>The <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-red-color\">classList.remove()<\/mark> method allows you to remove one or more class names from an HTML element.<\/p>\n\n\n\n<p>Similar to the <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-red-color\">add()<\/mark> method, the <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-red-color\">remove()<\/mark> method also accepts at least one string argument separated by commas.<\/p>\n\n\n\n<pre class=\"line-numbers language-js\"><code>\n\/* Get the navigation by id *\/\nconst navigation = document.querySelector('#navigation');\n\n\/* remove three class names *\/\nnavigation.classList.remove('navbar', 'open', 'close');\n<\/code><\/pre>\n\n\n\n<p>When removing a class that doesn&#8217;t exist JavaScript won&#8217;t throw an error.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\" id=\"classlist-toggle-method\">classList toggle() method<\/h4>\n\n\n\n<p>The <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-red-color\">classList.toggle()<\/mark> method allows you to add or remove a class name based on the current <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-red-color\">class<\/mark> value on the element.<\/p>\n\n\n\n<p>If the class name already exists on the element, the <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-red-color\">toggle()<\/mark> method will remove that class name and vice versa.<\/p>\n\n\n\n<p>Suppose you have an <strong>&lt;h1&gt;<\/strong> element with some text<\/p>\n\n\n\n<pre class=\"language-html\"><code>\n    &lt;h1 id=\"color\" class=\"pink\"&gt;Please choose a color&lt;\/h1&gt;\n<\/code><\/pre>\n\n\n\n<p>You can call the <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-red-color\">toggle()<\/mark> method on the heading to remove the class <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-purple-color\">&#8220;pink&#8221;<\/mark> from the element.<\/p>\n\n\n\n<pre class=\"line-numbers language-js\"><code>\n\/* Get the heading element for the DOM *\/\nconst heading = document.getElementById('color');\n\nheading.classList.toggle('pink'); \/\/=&gt; false\nheading.classList.toggle('pink'); \/\/=&gt; true\n<\/code><\/pre>\n\n\n\n<p>When the <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-red-color\">toggle()<\/mark> method removes a class, it will return <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-red-color\">false<\/mark>. Also, when it adds a class, it will return <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-red-color\">true<\/mark>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"removing-elements-from-the-dom\">Removing Elements from the DOM<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"remove\">remove()<\/h3>\n\n\n\n<p>The <strong>Element.remove()<\/strong> method removes the element from the DOM.<\/p>\n\n\n\n<p><strong>Syntax<\/strong> <code>remove()<\/code><\/p>\n\n\n\n<p>Suppose we have this HTML<\/p>\n\n\n\n<pre class=\"line-numbers language-html\"><code>\n&lt;!DOCTYPE html&gt;\n&lt;html lang=\"en\"&gt;\n  &lt;head&gt;\n    &lt;title&gt;Data Attribute&lt;\/title&gt;\n  &lt;\/head&gt;\n  &lt;script src=\".\/test.js\" defer&gt;&lt;\/script&gt;\n  &lt;body&gt;\n    &lt;div id=\"blue\"&gt;Blue books&lt;\/div&gt;\n    &lt;div id=\"orange\"&gt;Orange mangoes&lt;\/div&gt;\n  &lt;\/body&gt;\n&lt;\/html&gt;\n\n<\/code><\/pre>\n\n\n\n<p>Then we want to remove the element with the id attribute of <strong>orange<\/strong><\/p>\n\n\n\n<pre class=\"line-numbers language-js\"><code>\n\/* Get the div element *\/\nconst orange = document.getElementById('orange');\n\n\/* Remove the element from the DOM *\/\norange.remove();\n<\/code><\/pre>\n\n\n\n<p>How it works<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>First we get the element to be removed from the DOM with <strong>getElementById()<\/strong> method<\/li>\n\n\n\n<li>Then, we call the <strong>remove()<\/strong> method on the element to remove it.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"removechild\">removeChild()<\/h3>\n\n\n\n<p>The <strong>removeChild()<\/strong> method removes a child node from the DOM and returns the removed node.<\/p>\n\n\n\n<p><strong>Syntax<\/strong> <code>removeChild(child);<\/code> <\/p>\n\n\n\n<p>Suppose we have this HTML<\/p>\n\n\n\n<pre class=\"line-numbers language-html\"><code>\n&lt;div class=\"colors\"&gt;\n  &lt;div id=\"blue\"&gt;Blue books&lt;\/div&gt;\n  &lt;div id=\"orange\"&gt;Orange mangoes&lt;\/div&gt;\n&lt;\/div&gt;\n<\/code><\/pre>\n\n\n\n<p>Then we want to remove the orange div from the colors div using <strong>removeChild()<\/strong><\/p>\n\n\n\n<pre class=\"line-numbers language-js\"><code>\n\/* Get the div element *\/\nconst orange = document.getElementById('orange');\n\n\/* Remove the child node from the DOM *\/\nif (orange.parentNode) {\n  orange.parentNode.removeChild(orange);\n}\n<\/code><\/pre>\n\n\n\n<p>How it works<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>First we get the orange element from the DOM<\/li>\n\n\n\n<li>Then we use an if statement to check if it has a parent<\/li>\n\n\n\n<li>Finally, if that condition is true then we call the <strong>removeChild()<\/strong> method on the orange parent div.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"video-tutorial-on-how-to-manipulate-the-dom\">Video Tutorial on How To Manipulate the DOM<\/h2>\n\n\n\n<figure class=\"wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio\"><div class=\"wp-block-embed__wrapper\">\n<iframe loading=\"lazy\" title=\"Learn DOM Manipulation In 18 Minutes\" width=\"719\" height=\"404\" src=\"https:\/\/www.youtube.com\/embed\/y17RuWkWdn8?feature=oembed&#038;enablejsapi=1&#038;origin=https:\/\/codevoweb.com\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" allowfullscreen><\/iframe>\n<\/div><\/figure>\n","protected":false},"excerpt":{"rendered":"<p>If you are a newbie to JavaScript you may have heard of the DOM (Document Object Model). But what exactly is the DOM? As a&#8230;<\/p>\n","protected":false},"author":1,"featured_media":387,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[46,19],"tags":[38,36,37,35],"class_list":["post-115","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-javascript","category-programming","tag-dom","tag-dom-methods","tag-javascript","tag-javascript-dom"],"acf":[],"_links":{"self":[{"href":"https:\/\/codevoweb.com\/wp-json\/wp\/v2\/posts\/115","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codevoweb.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codevoweb.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codevoweb.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/codevoweb.com\/wp-json\/wp\/v2\/comments?post=115"}],"version-history":[{"count":1,"href":"https:\/\/codevoweb.com\/wp-json\/wp\/v2\/posts\/115\/revisions"}],"predecessor-version":[{"id":11326,"href":"https:\/\/codevoweb.com\/wp-json\/wp\/v2\/posts\/115\/revisions\/11326"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codevoweb.com\/wp-json\/wp\/v2\/media\/387"}],"wp:attachment":[{"href":"https:\/\/codevoweb.com\/wp-json\/wp\/v2\/media?parent=115"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codevoweb.com\/wp-json\/wp\/v2\/categories?post=115"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codevoweb.com\/wp-json\/wp\/v2\/tags?post=115"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}