Reputation: 477
I need a little help in javascript.
Actually, I want to add the list item to in the ul tag given in the HTML, with the help of javascript. When I click on the button it should add the element in the ul tag.
Here is the code for HTML-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<input type="text" id="insertTheElement" placeholder="Enter Text Here...">
<br><br><br>
<button id="upperMostButton" onclick="listItem()">Add The Content</button>
<ul id="onlyThisOne">
</ul>
<script src="main.js"></script>
</body>
</html>
Here Goes the code for JavaScript-
var contentOfList=document.getElementById('insertTheElement').value;
function listItem(contentOfList){
var AddingListItem=document.createElement('li');
AddingListItem.innerText=contentOfList;
document.body.ul.appendChild(AddingListItem);
}
Upvotes: 0
Views: 143
Reputation: 1773
Your code has some issues, you have written the function with input argument, that was not passed, which might have caused undefined items to be appended to your ul element. Moreover you can refer your ul interms of its id inorder to avoid confusion in future when there may be more than one ul element in your page, you can try the following code to achieve your requirement.
function listItem(){
var contentOfList=document.getElementById('insertTheElement').value;
var AddingListItem=document.createElement('li');
AddingListItem.innerText=contentOfList;
document.getElementById('onlyThisOne').appendChild(AddingListItem);
}
<input type="text" id="insertTheElement" placeholder="Enter Text Here...">
<br><br><br>
<button id="upperMostButton" onclick="listItem()">Add The Content</button>
<ul id="onlyThisOne">
</ul>
Upvotes: 1
Reputation: 6366
document.body.ul
makes no sense. If you need to find direct children of an HTML Element
you should use .children
.
Also, you need to get the value of the input element inside the function as this is a one-time copy of value, not a bound variable.
See the snippet below
function listItem(contentOfList) {
var contentOfList = document.getElementById('insertTheElement').value;
var AddingListItem = document.createElement('li');
AddingListItem.innerText = contentOfList;
document.getElementById('onlyThisOne').appendChild(AddingListItem);
}
<input type="text" id="insertTheElement" placeholder="Enter Text Here..." />
<button id="upperMostButton" onclick="listItem()">Add The Content</button>
<ul id="onlyThisOne">
</ul>
Upvotes: 0