Touching on JavaScript DOM

Touching on JavaScript DOM

with code example!

ยท

2 min read

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

ย