
Play Store Application link β Java to JavaScript in 13 Steps – App on Google Play
DOM (Document Object Model) is a programming interface for HTML and XML documents. It represents the page so that programs can change the document structure, style, and content. JavaScript can access and modify the DOM of a page using the Document object.
DOM Manipulation:
DOM manipulation involves creating, modifying, and deleting HTML elements on a web page dynamically using JavaScript. This is similar to working with collections and objects in core Java.
- Core Java Comparison: Think of the DOM as a data structure like a
HashMap
in core Java, where you can dynamically add, modify, or remove entries. Just as you might use methods likeput()
andremove()
with aHashMap
, you use JavaScript methods to manipulate the DOM.
Example Program:
Adding a new element to the DOM:
<!DOCTYPE html>
<html>
<head>
<title>DOM Manipulation</title>
<script>
function addElement() {
var newDiv = document.createElement("div");
var newContent = document.createTextNode("Hello, World!");
newDiv.appendChild(newContent);
document.body.appendChild(newDiv);
}
</script>
</head>
<body>
<button onclick="addElement()">Add Element</button>
</body>
</html>
Events:
Events are user interactions or system notifications that occur on a web page, such as clicks, key presses, or page loading. JavaScript can listen to and respond to these events using event handlers.
- Core Java Comparison: Handling events in JavaScript is like using event listeners in core Java, such as implementing
ActionListener
for a button click. Instead of registering an action listener on a button in a GUI, you use event listeners to handle actions in the web environment.
Example Programs:
Responding to a click event:
<!DOCTYPE html>
<html>
<head>
<title>Events</title>
<script>
function handleClick() {
alert("Button clicked!");
}
</script>
</head>
<body>
<button onclick="handleClick()">Click me</button>
</body>
</html>
Responding to a key press event:
<!DOCTYPE html>
<html>
<head>
<title>Events</title>
<script>
document.addEventListener("keydown", function(event) {
if (event.key === "Enter") {
alert("Enter key pressed!");
}
});
</script>
</head>
<body>
<p>Press the Enter key.</p>
</body>
</html>
To run these programs in Visual Studio Code, save them with a .html
extension and open them in a web browser. Alternatively, you can install the Live Server extension in Visual Studio Code and run them using the Live Server feature.