<!-- Learn about this code on MDN: https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement -->
<!DOCTYPE html>
<html>
<head>
<title>||Working with elements||</title>
</head>
<body>
<div id="div1">The text above has been created dynamically.</div>
</body>
</html>
JavaScript
document.body.onload = addElement;
function addElement () {
// create a new div element
// and give it some content
var opt=['a','b','c','d'];
var newDiv = document.createElement("div");
var newContent = document.createTextNode("Hi there and greetings!");
newDiv.appendChild(newContent); //add the text node to the newly created div.
var newsel=document.createElement("select");
newsel.addEventListener('click',function(){
//alert('click');
var options = newsel.querySelectorAll("option");
var count = options.length;
if(typeof(count) === "undefined" || count < 2)
{
for(var i = 0; i < opt.length; i++) {
var optn = document.createElement('option');
optn.innerHTML = opt[i];
optn.value = opt[i];
newsel.appendChild(optn);
}
}
});
newsel.addEventListener('change',function(){
alert('change');
var options = newsel.querySelectorAll("option");
var count = options.length;
if(typeof(count) != "undefined" || count > 1)
{
alert('on options change');
}
});
newDiv.appendChild(newsel);
// add the newly created element and its content into the DOM
var currentDiv = document.getElementById("div1");
document.body.insertBefore(newDiv, currentDiv);
}
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.