js add element code example
Example 1: js add class
var element = document.getElementById('element');
element.classList.add('class-1');
element.classList.add('class-2', 'class-3');
element.classList.remove('class-3');
Example 2: js create element
let myElm = document.createElement("p"); // Create a new element
myElm.innerText = 'test'; // Change the text of the element
myElm.style.color = 'red'; // Change the text color of the element
document.body.appendChild(myElm); // Add the object to the DOM
Example 3: add element to body javascript
var elem = document.createElement('div');
elem.style.cssText = 'position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000';
document.body.appendChild(elem);
Example 4: JavaScript append text to div
var div = document.getElementById('myElementID');
div.innerHTML += "Here is some more data appended";
Example 5: how to add elements in javascript html
//adding 'p' tag to body
var tag = document.createElement("p"); // <p></p>
var text = document.createTextNode("TEST TEXT");
tag.appendChild(text); // <p>TEST TEXT</p>
var element = document.getElementsByTagName("body")[0];
element.appendChild(tag); // <body> <p>TEST TEXT</p> </body>
Example 6: code for adding new elements in javascriipt js
<html>
<head>
<title>t1</title>
<script type="text/javascript">
function addNode()
{var newP = document.createElement("p");
var textNode = document.createTextNode(" This is a new text node");
newP.appendChild(textNode);
document.getElementById("firstP").appendChild(newP); }
</script> </head>
<body> <p id="firstP">firstP<p> </body>
</html>