javascript add object to dom element code example
Example 1: javascript append to paragraph
// In the JS script
var parElement = document.getElementById("myPar");
var textToAdd = document.createTextNode("Text to be added");
parElement.appendChild(textToAdd);
//In the HTML file
<p id="myPar"></p>
Example 2: javascript add div
<div id="new">
<p id="p1">Tutorix</p>
<p id="p2">Tutorialspoint</p>
</div>
<script>
var tag = document.createElement("p");
var text = document.createTextNode("Tutorix is the best e-learning platform");
tag.appendChild(text);
var element = document.getElementById("new");
element.appendChild(tag);
</script>
Example 3: adding element to javascript object
let person = {
name : 'John Doe',
age : 35
}
//Now we can add element by 2 ways
person.occupation = 'Web Designer'
//or
person['occupation'] = 'Web Designer'; //This is usefull for adding element within loop.
object[yourKey] = yourValue;
object.yourKey = yourValue;