The JavaScript DOM 15 Simple Code Examples

The JavaScript Document Object Model (DOM) is a programming interface for HTML and XML documents. It represents the structure of a document as a tree of objects, with each object (or “node”) representing a part of the document, such as an element, an attribute, or text content. The DOM allows developers to access and manipulate the contents of a document, as well as respond to events and create dynamic content.

The DOM is typically used in combination with JavaScript, as it allows developers to programmatically change the structure and content of a document. For example, a developer might use the DOM to change the text of a heading, add a new element to the page, or change the style of an element.

To work with the DOM, a developer must first access the root node of the document, which is typically the <html> element. From there, they can traverse the tree of nodes to access and manipulate specific elements of the document. The DOM provides a number of methods and properties that can be used to access and manipulate the nodes of the tree.

The DOM also provides a way to respond to events that occur in the document, such as a user clicking on a button or a page finishing loading. Developers can use event listeners to listen for specific events and then execute code in response.

In summary, the JavaScript DOM is a programming interface for HTML and XML documents that allows developers to access, manipulate, and respond to the contents of a document. It represents the structure of a document as a tree of objects, with each object representing a part of the document, it allows developers to programmatically change the structure and content of a document, and respond to events on the page.

examples of using the DOM with JavaScript:

  1. Accessing an element by its ID:
Copy code// Get the element with the ID "myHeading"
var heading = document.getElementById("myHeading");

// Change the text of the element
heading.innerHTML = "New heading text";
  1. Accessing elements by their class name:
Copy code// Get all elements with the class "myClass"
var elements = document.getElementsByClassName("myClass");

// Change the text of the first element with the class "myClass"
elements[0].innerHTML = "New text";
  1. Adding an event listener:
Copy code// Get the button element
var button = document.getElementById("myButton");

// Add a click event listener to the button
button.addEventListener("click", function() {
  alert("Button was clicked!");
});
  1. Changing the style of an element:
Copy code// Get the element
var element = document.getElementById("myElement");

// Change the background color of the element
element.style.backgroundColor = "blue";
  1. Traversing the DOM tree
Copy code// Get the first child of an element
var firstChild = element.firstChild;

// Get the parent of an element
var parent = element.parentNode;

// Get the next sibling of an element
var nextSibling = element.nextSibling;

Please note that the above code is just an example and it will only work if there’s an existing html structure that matches the selectors. Also keep in mind that the examples are simplified and in real-world scenario’s you’ll probably need to add error handling and conditionals to make sure you’re selecting the right elements.

10 Commonly used examples of how the DOM works

examples of using the DOM with JavaScript:

  1. Creating a new element:
Copy code// Create a new <p> element
var newParagraph = document.createElement("p");

// Add text to the new element
newParagraph.innerHTML = "This is a new paragraph";

// Append the new element to the body
document.body.appendChild(newParagraph);
  1. Removing an element:
Copy code// Get the element to remove
var elementToRemove = document.getElementById("elementToRemove");

// Remove the element
elementToRemove.parentNode.removeChild(elementToRemove);
  1. Replacing an element:
Copy code// Get the element to replace
var elementToReplace = document.getElementById("elementToReplace");

// Create a new element
var newElement = document.createElement("div");

// Replace the old element with the new element
elementToReplace.parentNode.replaceChild(newElement, elementToReplace);
  1. Accessing the value of an input element:
Copy code// Get the input element
var input = document.getElementById("myInput");

// Get the value of the input
var inputValue = input.value;

// Set the value of the input
input.value = "New value";
  1. Changing the class of an element:
Copy code// Get the element
var element = document.getElementById("myElement");

// Add a class to the element
element.classList.add("new-class");

// Remove a class from the element
element.classList.remove("old-class");

// Toggle a class on an element
element.classList.toggle("toggle-class");
  1. Changing the attribute of an element:
Copy code// Get the element
var element = document.getElementById("myElement");

// Get the value of an attribute
var attributeValue = element.getAttribute("href");

// Set the value of an attribute
element.setAttribute("href", "https://www.example.com");
  1. Getting the position of an element:
Copy code// Get the element
var element = document.getElementById("myElement");

// Get the position of the element
var rect = element.getBoundingClientRect();

// Get the x and y position
var xPos = rect.left + window.pageXOffset;
var yPos = rect.top + window.pageYOffset;
  1. Changing the CSS of an element:
Copy code// Get the element
var element = document.getElementById("myElement");

// Change the CSS of the element
element.style.cssText = "color: red; font-size: 20px;";
  1. Traversing the DOM tree using querySelector:
Copy code// Get the first element that matches the selector
var element = document.querySelector("#myId .myClass");

// Get all the elements that match the selector
var elements = document.querySelectorAll(".myClass");

10. DOM to manipulate a table:

Copy code// Get the table element
var table = document.getElementById("myTable");

// Get the first row of the table
var firstRow = table.rows[0];

// Get the first cell of the first row
var firstCell = firstRow.cells[0];

// Change the text of the first cell
firstCell.innerHTML = "New text";

// Add a new row to the table
var newRow = table.insertRow(-1);

// Add a new cell to the new row
var newCell = newRow.insertCell(0);

// Add text to the new cell
newCell.innerHTML = "New cell text";

Please note that the above code is just an example and it will only work if there’s an existing html structure that matches the selectors. Also keep in mind that the examples are simplified and in real-world scenario’s you’ll probably need to add error handling and conditionals to make sure you’re selecting the right elements. Also, note that the table.rows property returns an HTMLCollection of rows in the table, while the table.insertRow() method allows you to insert a new row at a specific position in the table.

More Examples of DOM and Table updates

Get all the rows in a table:

Copy code// Get the table

var table = document.getElementById(“myTable”);

// Get all the rows in the table

var rows = table.getElementsByTagName(“tr”);

Delete a row from a table:

Copy code// Get the row to delete

var rowToDelete = table.rows[3];

// Delete the row

table.deleteRow(rowToDelete.rowIndex);

Modifying table cells:

Copy code// Get the cell

var cell = table.rows[2].cells[1];

// Change the text of the cell

cell.innerHTML = “New cell text”;

// Change the background color of the cell

cell.style.backgroundColor = “lightgray”;

Get all the cells in a row:

Copy code// Get the row

var row = table.rows[2];

// Get all the cells in the row

var cells = row.getElementsByTagName(“td”);

Get all the cells in a column:

Copy code// Get the cells of the first column

var columnCells = table.getElementsByTagName(“th”);

for(var i = 0; i < columnCells.length; i++){

  console.log(columnCells[i].innerHTML);

}

Modifying table headers:

Copy code// Get the header cell

var header = table.rows[0].cells[1];

// Change the text of the header

header.innerHTML = “New header text”;

// Change the font size of the header

header.style.fontSize = “20px”;

Add a new table column:

Copy code// Add a new table column

var newCol = table.createTHead().insertRow(-1).insertCell(-1);

// Add text to the new column

newCol.innerHTML = “New Column”;

Delete a table column:

Copy code// Get the column to delete

var colToDelete = table.rows[0].cells[1];

// Delete the column

colToDelete.parentNode.removeChild(colToDelete);

DOM examples

Accessing the text content of an element:

Copy code// Get the element

var element = document.getElementById(“myElement”);

// Get the text content of the element

var textContent = element.textContent;

// Set the text content of the element

element.textContent = “New text content”;

Changing the value of a select element:

Copy code// Get the select element

var select = document.getElementById(“mySelect”);

// Get the selected option

var selectedOption = select.options[select.selectedIndex];

// Change the selected option

select.selectedIndex = 2;

Checking if an element has a specific class:

Copy code// Get the element

var element = document.getElementById(“myElement”);

// Check if the element has the class “myClass”

if (element.classList.contains(“myClass”)) {

  console.log(“The element has the class ‘myClass’.”);

}

Getting the children of an element:

Copy code// Get the parent element

var parent = document.getElementById(“myParent”);

// Get the children of the parent element

var children = parent.children;

Cloning an element:

Copy code// Get the element to clone

var element = document.getElementById(“myElement”);

// Clone the element

var clonedElement = element.cloneNode(true);

// Append the cloned element to the body

document.body.appendChild(clonedElement);

Getting the previous and next siblings of an element:

Copy code// Get the element

var element = document.getElementById(“myElement”);

// Get the previous sibling of the element

var previousSibling = element.previousElementSibling;

// Get the next sibling of the element

var nextSibling = element.nextElementSibling;

Getting the parent element of an element:

Copy code// Get the element

var element = document.getElementById(“myElement”);

// Get the parent element

var parent = element.parentElement;

Modifying the HTML content of an element:

Copy code// Get the element

var element = document.getElementById(“myElement”);

// Get the HTML content of the element

var innerHTML = element.innerHTML;

// Set the HTML content of the element

element.innerHTML = “<p>New HTML content</p>”;

Setting a data attribute of an element:

Copy code// Get the element

var element = document.getElementById(“myElement”);

// Set a data attribute of the element

element.setAttribute(“data-my-attribute”, “some value”);

// Get the value of the data attribute

var dataAttributeValue = element.getAttribute(“data-my-attribute”);

Hiding an element:

Copy code// Get the element to hide

var element = document.getElementById(“myElement”);

// Hide the element

element.style.display = “none”;

Showing a hidden element:

Copy code// Get the hidden element

var hiddenElement = document.getElementById(“myHiddenElement”);

// Show the element

hiddenElement.style.display = “block”;

Creating a new option in a select element:

Copy code// Get the select element

var select = document.getElementById(“mySelect”);

// Create a new option element

var option = document.createElement(“option”);

// Set the value and text of the option

option.value = “newOptionValue”;

option.text = “New Option”;

// Add the option to the select element

select.add(option);

Removing an option from a select element:

Copy code// Get the select element

var select = document.getElementById(“mySelect”);

// Get the option to remove

var optionToRemove = select.options[1];

// Remove the option from the select element

select.remove(optionToRemove.index);

Getting the selected option from a select element:

Copy code// Get the select element

var select = document.getElementById(“mySelect”);

// Get the selected option

var selectedOption = select.options[select.selectedIndex];

// Get the value and text of the selected option

var selectedValue = selectedOption.value;

var selectedText = selectedOption.text;

Creating a new form element:

Copy code// Create a new input element

var input = document.createElement(“input”);

// Set the type and value of the input

input.type = “text”;

input.value = “New Input”;

// Append the input to the form

var form = document.getElementById(“myForm”);

form.appendChild(input);

Getting the value of a form element:

Copy code// Get the form element

var element = document.getElementById(“myFormElement”);

// Get the value of the form element

var value = element.value;

Setting the value of a form element:

Copy code// Get the form element

var element = document.getElementById(“myFormElement”);

// Set the value of the form element

element.value = “New Value”;

Creating a new image element:

Copy code// Create a new image element

var img = document.createElement(“img”);

// Set the source and alt text of the image

img.src = “image.jpg”;

img.alt = “New Image”;

// Append the image to the body

document.body.appendChild(img);

Using querySelectorAll to get all elements with a specific class:

Copy code// Get all elements with class “my-class”

var elements = document.querySelectorAll(“.my-class”);

// Change the text of all elements

for (var i = 0; i < elements.length; i++) {

  elements[i].innerHTML = “New text”;

}

Using innerHTML to insert HTML content:

Copy code// Get the element

var element = document.getElementById(“myElement”);

// Insert HTML content

element.innerHTML = “<p>This is a new paragraph.</p><img src=’image.jpg’>”;

Using textContent to insert text content:

Copy code// Get the element

var element = document.getElementById(“myElement”);

// Insert text content

element.textContent = “This is some text.”;

Using createTextNode to create a text node:

Copy code// Create a text node

var textNode = document.createTextNode(“This is some text.”);

// Append the text node to an element

var element = document.getElementById(“myElement”);

element.appendChild(textNode);

Using getElementsByTagName to get elements by tag name:

Copy code// Get all <p> elements

var elements = document.getElementsByTagName(“p”);

// Change the text of all <p> elements

for (var i = 0; i < elements.length; i++) {

  elements[i].innerHTML = “New text”;

}

Using getElementsByName to get elements by name:

Copy code// Get all elements with name “myName”

var elements = document.getElementsByName(“myName”);

// Change the value of all elements

for (var i = 0; i < elements.length; i++) {

  elements[i].value = “New value”;

}

Using parentNode to access the parent of an element:

Copy code// Get the element

var element = document.getElementById(“myElement”);

// Get the parent of the element

var parent = element.parentNode;

// Change the class of the parent

parent.classList.add(“new-class”);

Using children to access the children of an element:

Copy code// Get the element

var element = document.getElementById(“myElement”);

// Get the children of the element

var children = element.children;

// Change the text of the first child

children[0].innerHTML = “New text”;

Using nextSibling to access the next sibling of an element:

Copy code// Get the element

var element = document.getElementById(“myElement”);

// Get the next sibling of the element

var nextSibling = element.nextSibling;

// Change the text of the next sibling

nextSibling.innerHTML = “New text”;