JavaScript DOM Code Examples V6
JavaScript DOM Code Examples V6
How can we create a new DOM element in JavaScript and add it to the page?
6
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
</head>
<body>
<p>Hello, world!</p>
<button id="myButton">Click me!</button>
<script src="script.js"></script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
</head>
<body>
<p id="myParagraph">Hello, world!</p>
<script src="script.js"></script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
<style>
#myDiv {
background-color: red;
color: white;
}
</style>
</head>
<body>
<div id="myDiv">Hello, world!</div>
<script src="script.js"></script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
</head>
<body>
<div id="myDiv">Hello, world!</div>
<script src="script.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
</head>
// Removing an element
const myDiv = document.getElementById('myDiv');
myDiv.remove();
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
</head>
In this example, we're getting the value of the input element with
an id of myInput using the value property, and logging it to the
console.
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
<style>
.myClass {
color: red;
}
</style>
</head>
<body>
<div id="myDiv" class="myClass">Hello, world!</div>
<script src="script.js"></script>
</body>
</html>
// Checking if an element has a specific class
const myDiv = document.getElementById('myDiv');
if (myDiv.classList.contains('myClass')) {
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
<style>
.myClass {
color: red;
}