Creating dynamic div using javascript - javascript

<script>
function selecteditems()
{
var i=1;
var val="";
while(i<=53)
{
if(document.getElementById('timedrpact'+i)!="")
{
val+=document.getElementById('timedrpact'+i).value;
document.getElementById('showselecteditems').innerHTML=val;
}
i++;
}
}
</script>
How to create a new div and add contents to it?In the above case i lost previous content due to innerHTML.I want new div each time for dynamically attach an image and the above variable val to it.
Thanks in advance.

Check this Demo
<div id="output" class="out">
</div>
window.onload=function(){
var output = document.getElementById('output');
var i=1;
var val="";
while(i<=3)
{
if(!document.getElementById('timedrpact'+i))
{
var ele = document.createElement("div");
ele.setAttribute("id","timedrpact"+i);
ele.setAttribute("class","inner");
ele.innerHTML="hi "+i;
output.appendChild(ele);
}
i++;
}
};

Look at document.createElement() and element.appendChild().
var newdiv = document.createElement("div");
newdiv.innerHTML = val;
document.getElementById("showselecteditems").appendChild(newdiv);
Because you will likely encounter this in the near future: You can remove any element with this code:
element.parentNode.removeChild(element);

Using createElement:
function selecteditems() {
var container = document.getElementById('showselecteditems');
for (var i=1;i<=53;i++) {
var fld = document.getElementById('timedrpact'+i);
if (fld) {
var div = document.createElement("div");
div.appendChild(document.createTextNode(fld.value));
container.appendChild(div);
}
}
}
Full version using cloneNode (faster) and eventBubbling
Live Demo
var div = document.createElement("div");
var lnk = document.createElement("a");
var img = document.createElement("img")
img.className="remove";
img.src = "https://uperform.sc.gov/ucontent/e14c3ba6e4e34d5e95953e6d16c30352_en-US/wi/xhtml/static/noteicon_7.png";
lnk.appendChild(img);
div.appendChild(lnk);
function getInputs() {
var container = document.getElementById('showselecteditems');
for (var i=1;i<=5;i++) {
var fld = document.getElementById('timedrpact'+i);
if (fld) {
var newDiv = div.cloneNode(true);
newDiv.getElementsByTagName("a")[0].appendChild(document.createTextNode(fld.value));
container.appendChild(newDiv);
}
}
}
window.onload=function() {
document.getElementById('showselecteditems').onclick = function(e) {
e=e||event;
var target = e.target||e.srcElement;
// target is the element that has been clicked
if (target && target.className=='remove') {
parentDiv = target.parentNode.parentNode;
parentDiv.parentNode.removeChild(parentDiv);
return false; // stop event from bubbling elsewhere
}
}
getInputs();
}

Syntax for dynamic create div:
DivId = document.createElement('div');
DivId.innerHtml ="text"

Related

JavaScript adding event on element generated element with innerHtml

I want to add an event on an element does doesn't exist in the original HTML (created with innerHtml). When i click nothing happens.
const btnRemove = document.getElementById("remove");
btnMow.addEventListener("click", function mow() {
if (sMow === true) {
reqServices.push("Mow Lawn");
service.innerHTML += `
<div class="v1">
<p class="v3-text">Mown Lawn <span id="remove">remove</span></p>
<p class="v3-dollar"><span>$</span>20</p>
</div>`;
sMow = false;
total += 20;
totalC();
}
});
btnRemove.addEventListener("click", function remove() {
alert("HELLO");
});
I want to add a click event on the element with id remove.
Another way to do that is creating the elements instead of use the HTML code and a later search. This maybe useful if you, for example, don't want to add an id to the remove tag
btnMow.addEventListener("click", function mow() {
if (sMow === true) {
reqServices.push("Mow Lawn");
var div = document.createElement("div");
div.className = "v1";
service.appendChild(div);
var p1 = document.createElement("p");
p1.className = "v3-text";
div.appendChild(p1);
var p1Text = document.createTextNode("Mown Lawn ");
p1.appendChild(p1Text);
var p1Span = document.createElement("span");
p1Span.setAttribute("id", "remove");
p1Span.innerText = "remove";
p1Span.addEventListener("click", function remove() {
alert("HELLO");
});
p1.appendChild(p1Span);
var p2 = document.createElement("p");
p2.className = "v3-dollar";
p2.innerHTML = "<span>$</span>20";
div.appendChild(p2);
sMow = false;
total += 20;
totalC();
}
});
As you can see, creating the elements allow you do whatever you want with it. It's longer but you can use a helper function like this:
function appendTag(parent, tagName, className) {
var tag = document.createElement(tagName);
if (className)
tag.className = className;
parent.appendChild(tag);
return tag;
}
And rewrite as:
btnMow.addEventListener("click", function mow() {
if (sMow === true) {
reqServices.push("Mow Lawn");
var div = appendTag(service, "div", "v1");
var p1 = appendTag(div, "p", "v3-text");
p1.appendChild(document.createTextNode("Mown Lawn "));
var p1Span = appendTag(p1, "span");
p1Span.setAttribute("id", "remove");
p1Span.innerText = "remove";
p1Span.addEventListener("click", function remove() {
alert("HELLO");
});
var p2 = appendTag(p1, "p", "v3-dollar");
p2.innerHTML = "<span>$</span>20";
sMow = false;
total += 20;
totalC();
}
});
btnMow.addEventListener("click", function mow() {
if (sMow === true) {
reqServices.push("Mow Lawn");
service.innerHTML += `
<div class="v1">
<p class="v3-text">Mown Lawn <span id="remove">remove</span></p>
<p class="v3-dollar"><span>$</span>20</p>
</div>`;
sMow = false;
total += 20;
totalC();
}
const btnRemove = document.getElementById("remove");
btnRemove.addEventListener("click", function remove() {
alert("HELLO");
});
});
var btnremove = document.getElementById("remove");
write this before starting click event

CreateElement then Removelement

I am creating a function that creates image when html button clicked and if click again on button it deletes created image instead. it doesn't delete when I click again on button .
any help would be appreciated.
a = 0;
function createimg() {
var newElement = document.createElement("img");
newElement.setAttribute("id", "img");
newElement.setAttribute("src", "shield.png");
var list = document.getElementById("img");
if (a == 0) {
document.body.appendChild(newElement);
a = 1;
} else
document.body.removeChild(newElement);
}
when you remove the element, remove 'list'
not 'newElement'
try this
a=0;
function createimg() {
if (a==0) {
var newElement = document.createElement("img");
newElement.setAttribute("id","img");
newElement.setAttribute("src","shield.png");
document.body.appendChild(newElement);
a=1;
} else {
var list= document.getElementById("img");
document.body.removeChild(list);
}
}

How to refer to a dynamically created div with JS

So I am creating div's onclick and giving them incrementally greater Id's. I want to then change the CSS properties of each div but I can't seem to select it with document.getElementById.
Obviously I'm missing something incredibly simple here, any advice or reading would be appreciated.
JS Fiddle
Some relevant Javascript:
function createDiv(){
i++;
var newDiv = document.createElement("div");
newDiv.id = "newDiv"+i;
var e = document.getElementById("newDiv1");
e.innerHTML = "hello";
e.className = "newDivs";
var x = 50*i;
e.style.left = x+"px";
e.style.top = 200+"px";
//but nothing appears
}
you have not attached your div to the DOM tree, you should first attach it then try to grab its reference:
function createDiv(){
i++;
var newDiv = document.createElement("div");
newDiv.id = "newDiv"+i;
document.body.appendChild(newDiv); // <--- Append it here
var e = document.getElementById("newDiv1");
e.innerHTML = "hello";
e.className = "newDivs";
var x = 50*i;
e.style.left = x+"px";
e.style.top = 200+"px";
//but nothing appears
}
You need to append the div into the dom see fiddle
http://jsfiddle.net/coqkg5oz/5/
function addDiv() {
var objTo = document.getElementById('container')
var divtest = document.createElement("div");
divtest.innerHTML = "new div"
objTo.appendChild(divtest)
}
You haven't added the element to the page, that's why it doesn't show up.
You don't need to use getElementById to get a reference to the element, as you already have a reference to the element.
Example:
function createDiv(){
i++;
var e = document.createElement("div");
e.id = "newDiv"+i;
document.body.appendChild(e);
e.innerHTML = "hello";
e.className = "newDivs";
var x = 50*i;
e.style.left = 100+"px";
e.style.top = 200+"px";
}
Demo: http://jsfiddle.net/Guffa/coqkg5oz/8/

Setting the onClick property dynamically

I am trying to set the onClick property of a dynamically generated div in a loop but the code below is not working beyond generating the divs. Can someone please help me out?
<script type="text/javascript">
function gengrid()
{
var i=0;
var num_stud=8;
var newdiv;
var divIdName;
var maindiv;
for(i=1;i<=num_stud;i++)
{
newdiv = document.createElement('div');
divIdName = '50'+i;
newdiv.setAttribute('id',divIdName);
newdiv.onClick= function(){addit(i);};
newdiv.innerHTML = '<img src=50'+i+'.jpg alt="a"></img>';
maindiv=document.getElementById('main');
maindiv.appendChild(newdiv);
}
}
gengrid();
function addit(picno)
{
alert(picno+'');
}
</script>
The onclick method should have a lowercase c.
See this fiddle: http://jsfiddle.net/MTpUV/
<script type="text/javascript">
function gengrid()
{
var i=0;
var num_stud=8;
var newdiv;
var divIdName;
var maindiv;
for(i=1;i<=num_stud;i++)
{
newdiv = document.createElement('div');
divIdName = '50'+i;
newdiv.setAttribute('id',divIdName);
newdiv.onclick= function(){addit(i);};
newdiv.innerHTML = '<img src=50'+i+'.jpg alt="a"></img>';
maindiv=document.getElementById('main');
maindiv.appendChild(newdiv);
}
}
gengrid();
function addit(picno)
{
alert(picno+'');
}
</script>

How to run a nested javascript function?

I am new to object orientated programming in javascript and am trying to understand some functions in a project I am working on.
How would I call/run the internal function (the one listed 'this.getFieldset = function() {') to execute?
function Fieldset() {
this.id = "";
this.content = document.createElement("DIV");
this.content.id = "content";
this.title = "Title";
this.getFieldset = function() {
var div = document.createElement("DIV");
div.id = this.id;
var span = document.createElement("SPAN");
var fieldset = document.createElement("DIV");
fieldset.id = "fieldset";
var header = document.createElement("DIV");
header.id = "header";
span.appendChild(document.createTextNode(this.title));
header.appendChild(span);
div.appendChild(header);
div.appendChild(this.content);
div.appendChild(fieldset);
return div;
}
}
var myFieldset = new Fieldset();
myFieldset.getFieldset();
First you should create an instance of Fieldset, then you'll be able to call its functions (called methods):
var myFieldset = new Fieldset();
myFieldset.getFieldset();
function Fieldset() {
this.id = "";
this.content = document.createElement("DIV");
this.content.id = "content";
this.title = "Title";
this.getFieldset = function() {
var div = document.createElement("DIV");
div.id = this.id;
var span = document.createElement("SPAN");
//var fieldset = document.createElement("DIV");
//fieldset.id = "fieldset";
var header = document.createElement("DIV");
header.id = "header";
span.appendChild(document.createTextNode(this.title));
header.appendChild(span);
div.appendChild(header);
div.appendChild(this.content);
div.appendChild(fieldset);
window.alert("test");
return div;
}
//add call to run function
this.getFieldset();
}

Categories

Resources