Skip to main content

Command Palette

Search for a command to run...

Touching on JavaScript DOM

with code example!

Published
2 min readView as Markdown
Touching on JavaScript DOM
D

🌍 African in Europe 💻 Designer & Developer 🤓 Always Learning 📱Apple Fanboy

The 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 representing a part of the document (such as an element, an attribute, or a piece of text).

JavaScript can be used to manipulate the DOM, allowing a developer to change the content, structure, and styling of a web page in response to user input or other events.

So, Diki like... what can we do with this?

Well, I am super glad you asked!

You can add a button to an HTML document using JavaScript and the DOM in the following way:

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

// Set the button text
button.innerHTML = "Click me";

// Add an event listener to the button
button.addEventListener("click", function(){
    alert("Button was clicked!");
});

// Append the button to a specific element on the page
var body = document.getElementsByTagName("body")[0];
body.appendChild(button);

Pretty cool, eh?

This code creates a new button element, sets its text to "Click me", adds a click event listener to it so that it will display an alert when clicked, and then appends it to the body of the HTML document.

You can change the text of the button to whatever you like and also add the button to any element on the page by replacing body with the element you want to add the button to.

via GIPHY

And that, my fellow developers, is the DOM in a nutshell!

Do you have any other cool examples of how to manipulate the DOM?
Let me know in the comments below!

Bye, for now! 👋 Diki

N

Clear explaining. Thank you

1
D
Dee3y ago

Glad you found it useful, Nihat!

1

JavaScript: Introduction to Hero

Part 9 of 9

In this series we will explain beginner to interview ready JavaScript concepts

Start from the beginning

Beginners Guide to JavaScript

A Quick guide to some JavaScript Key Concepts

More from this blog

D

diki the dev

24 posts

Topics I write about: HTML, CSS & JavaScript As a designer I became frustrated not being able to code my own designs. This sparked the desire for me to dive into full stack JavaScript development.