Tworzenie elementu html z klasą z funkcją ich usunięcia po kliknięciu
<!DOCTYPE html>
<html lang="pl">
<head>
<meta charset="UTF-8">
<title>Page Title</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="main_title">Main title</div>
<p>This is an intro</p>
<button onclick="addDiv()">Click me</button>
<p id="intro">This is an article</p>
<script type="text/javascript" src="main.js"></script>
</body>
</html>
function addDiv(){
let div = document.createElement('div');
div.className = "test";
div.innerHTML = "<p class='klasa'>text</p>";
document.body.appendChild(div);
div.addEventListener("click", deleteDiv);
}
function deleteDiv(){
this.remove();
}
Dodawanie obiektów do określonego kontenera z numeracją
<!DOCTYPE html>
<html lang="pl">
<head>
<meta charset="UTF-8">
<title>Page Title</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="main_title" >Main title</div>
<p>This is an intro</p>
<button onclick="addDiv()">Click me</button>
<div id="parent"></div>
<p id="intro">This is an article</p>
<script type="text/javascript" src="main.js"></script>
</body>
</html>
let nr = 0;
function addDiv(){
const parent = document.getElementById("parent");
if(parent){
let div = document.createElement('p');
div.className = "test";
div.innerHTML = "<p class='klasa'>text" + nr + "</p>";
parent.appendChild(div);
div.addEventListener("click", deleteDiv);
nr++;
}
}
function deleteDiv(){
this.remove();
}
Tworzenie i usuwanie elementów div w javascript – przykład
<!DOCTYPE html>
<html lang="pl">
<meta charset="UTF-8">
<title>Page Title</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<style>
.main{
text-align: center;
}
#test{
text-align: center;
width:400px;
height: 300px;
margin:10px auto;
}
#cancel{
text-align: center;
border:2px solid red;
padding: 10px;
width:200px;
margin:0 auto;
}
</style>
<script>
var popup, cancel;
function popUp() {
popup = document.createElement('div');
popup.id = 'test';
popup.innerHTML = "This is a test message";
popup.style.border = "2px solid #0000FF";
cancel = document.createElement('div');
cancel.id = 'cancel';
cancel.innerHTML = "Cancel";
cancel.onclick= destroyElements;
document.body.appendChild(popup);
document.body.appendChild(cancel);
}
function destroyElements(){
popup.remove();
cancel.remove();
}
</script>
<body>
<div class="main">
<button id="popupButton" onclick="popUp()">click here</button>
</div>
</body>
</html>