How to create element in javascript?
addEventListener Javascript example: In JavaScript we can create element and use function as a click event or other event. Also get element value from the without id get value from the direct or with querySelector method.
See below example for the basic javascript code:-
Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Basic Javascript</title>
<link href="app.css" rel="stylesheet" />
<script async src="app.js"></script>
</head>
<body>
<div class="box-container">
<div class="box-input">
<input type="text">
</div>
<div class="box-submit">
<button type="submit">Add Courses</button>
</div>
<ul>
</ul>
<div id="dataAdded"> </div>
</div>
</body>
</html>
app.css
.box-container{
border: 1px solid #ccc;
padding: 20px;
margin: 50px auto;
max-width: 400px;
border-radius: 5px;
box-shadow: 0 0 10px 0 #aaa;
text-align: center;
}
.box-input input[type='text']{
border: 1px solid #ccc;
padding: 5px 10px;
width: 100%;
box-sizing: border-box;
margin-bottom: 15px;
text-align: left;
color: #333;
font-size: 16px;
font-weight: 700;
}
.box-submit button[type='submit']{
border: 0;
padding: 5px 10px;
text-align: center;
color: #fff;
background: #0bf;
cursor: pointer;
}
ul{
margin: 0;
list-style: none;
padding: 0;
}
ul li{
display: block;
border: 1px solid #eee;
padding: 10px;
border-radius: 3px;
text-align: left;
margin: 10px 0;
font-family: Arial, Helvetica, sans-serif;
}
#dataAdded div{
border: 1px solid #eee;
padding: 10px;
border-radius: 3px;
text-align: left;
margin: 10px 0;
font-family: Arial, Helvetica, sans-serif;
}
app.js
const buttonEle = document.querySelector('button');
const inputEle = document.querySelector('input');
const listEle = document.querySelector('ul');
function addCourse() {
//console.log('1')
const enterdValue = inputEle.value;
const listItemEl = document.createElement('li');
console.log(enterdValue);
listItemEl.textContent = enterdValue;
listEle.appendChild(listItemEl);
inputEle.value = ''
}
buttonEle.addEventListener('click', addCourse);
....................................
const btnEle = document.querySelector('button');
const inputEle = document.querySelector('input');
const dataShow = document.getElementById('dataAdded');
function addCourse(){
const enteredValue = inputEle.value;
const textHolder = document.createElement('div');
textHolder.textContent = enteredValue;
dataShow.appendChild(textHolder);
}
btnEle.addEventListener('click',addCourse);
No comments:
Note: Only a member of this blog may post a comment.