create element div in javascript code example
Example 1: js create element
let myElm = document.createElement("p");
myElm.innerText = 'test';
myElm.style.color = 'red';
document.body.appendChild(myElm);
Example 2: js create div
document.body.onload = addElement;
function addElement () {
const newDiv = document.createElement("div");
const newContent = document.createTextNode("Hi there and greetings!");
newDiv.appendChild(newContent);
const currentDiv = document.getElementById("div1");
document.body.insertBefore(newDiv, currentDiv);
}
Example 3: javascript create div in div
Your code works well you just mistyped this line of code:
document.getElementbyId('lc').appendChild(element);
change it with this: (The "B" should be capitalized.)
document.getElementById('lc').appendChild(element);
HERE IS MY EXAMPLE:
<html>
<head>
<script>
function test() {
var element = document.createElement("div");
element.appendChild(document.createTextNode('The man who mistook his wife for a hat'));
document.getElementById('lc').appendChild(element);
}
</script>
</head>
<body>
<input id="filter" type="text" placeholder="Enter your filter text here.." onkeyup = "test()" />
<div id="lc" style="background: blue; height: 150px; width: 150px;
}" onclick="test();">
</div>
</body>
</html>
Example 4: create and append element in javascript
var node = document.createElement("LI");
var textnode = document.createTextNode("Water");
node.appendChild(textnode);
document.getElementById("myList").appendChild(node);