Ads Top

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{
    border1px solid #ccc;
    padding20px;
    margin50px auto;
    max-width400px;
    border-radius5px;
    box-shadow0 0 10px 0 #aaa;
    text-aligncenter;
}
.box-input input[type='text']{
    border1px solid #ccc;
    padding5px 10px;
    width100%;
    box-sizingborder-box;
    margin-bottom15px;
    text-alignleft;
    color#333;
    font-size16px;
    font-weight700;
}
.box-submit button[type='submit']{
    border0;
    padding5px 10px;
    text-aligncenter;
    color#fff;
    background#0bf;
    cursorpointer;
}
ul{
    margin0;
    list-stylenone;
    padding0;
}
ul li{
    displayblock;
    border1px solid #eee;
    padding10px;
    border-radius3px;
    text-alignleft;
    margin10px 0;
    font-familyArialHelveticasans-serif;
}
#dataAdded div
    border1px solid #eee;
    padding10px;
    border-radius3px;
    text-alignleft;
    margin10px 0;
    font-familyArialHelveticasans-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);

You will be find result:



No comments:

Note: Only a member of this blog may post a comment.

Copyright Reserved to Anything Learn. Powered by Blogger.