How to add multiple div dynamically with append child having different id? - javascript

I am trying to add div on clicking add button.
on clicking add button the div is created with the
class name ui modal and
id test.
For multiple div created the same id gets added.
I need to give different ID for Each additionally added div.
How can I generate different ID using append child.
Also I need to get the tree structure with parent child and sibling node.
function add_div(){
var div = document.createElement('div');
document.body.appendChild(div);
div.className = 'ui-modal';
div.id = 'test';
div.innerHTML = '<span class="msg">Hello world.</span>';
div.textContent = 'Hello world.';
}
.ui-modal{
width: 200px;
height: 50px;
border: 1px solid red;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="wrapper">
<input type="button" value="ADD" onclick="add_div();">
<input type="button" value="DELETE">
</div>
</body>
</html>
After running this above code And inspecting i am seeing each additionally added div having same ID.
How to generate separate ID?

You can declare a counter outside add_div and append it into id everytime you create a div
var counter = 1;
function add_div(){
var div = document.createElement('div');
document.body.appendChild(div);
div.className = 'ui-modal';
div.id = 'test' + (counter++);
div.innerHTML = '<span class="msg">Hello world.</span>';
div.textContent = 'Hello world.';
}
.ui-modal{
width: 200px;
height: 50px;
border: 1px solid red;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="wrapper">
<input type="button" value="ADD" onclick="add_div();">
<input type="button" value="DELETE">
</div>
</body>
</html>

You can use the length of elements with class img to use that as the suffix to the id:
function add_div(){
var div = document.createElement('div');
document.body.appendChild(div);
div.className = 'ui-modal';
div.id = 'test-' + document.querySelectorAll('.ui-modal > .msg').length;
div.innerHTML = '<span class="msg">Hello world.</span>';
//div.textContent = 'Hello world.';
}
.ui-modal{
width: 200px;
height: 50px;
border: 1px solid red;
}
<div class="wrapper">
<input type="button" value="ADD" onclick="add_div();">
<input type="button" value="DELETE">
</div>

Related

How to add CSS to elements after form submission using JS

I am currently creating a meme generator app where the user can submit an image, as well as top and bottom text. I want to make it so that after form submission, the text is added onto the image and styled using CSS. I have already tried adding a class to the elements and adding css to it but that does not work. Here is my code:
JS
let form = document.querySelector('#meme-form');
let img = document.querySelector('#img');
let topTxt = document.querySelector('#top-txt');
let bottomTxt = document.querySelector('#bottom-txt');
form.addEventListener('submit', function(e) {
e.preventDefault();
let memePic = document.createElement('img');
//create the divs for the memes
let newDiv = document.createElement('div');
form.appendChild(newDiv);
topTxt.classList.add('top')
bottomTxt.classList.add('bottom')
memePic.src = img.value;
newDiv.append(memePic, topTxt.value, bottomTxt.value);
//set the textbox inputs equal to nothing
img.value = '';
topTxt.value = '';
bottomTxt.value= '';
})
CSS
div {
width: 30%;
height: 300px;
margin: 10px;
display: inline-block;
}
img {
width: 100%;
height: 100%;
margin: 10px;
display: inline-block;
}
.top{
color: blue;
}
#bottom-txt {
color: red;
}
HTML
<body>
<form action="" id="meme-form">
<label for="image">img url here</label>
<input id="img" type="url"><br>
<label for="top-text">top text here</label>
<input id="top-txt" type="text"><br>
<label for="bottom-text">bottom text here</label>
<input id="bottom-txt" type="text"><br>
<input type="submit"><br>
</form>
<script src="meme.js"></script>
</body>
</html>
You just need to fix up some of logic how the elements are being appended after form is submitted.
For that you need to div after your form which will hold you results and then order your element to be displayed. I have also added a line hr to have separator between each results displayed.
You can style your element the way you would like them to be - i have added some basic CSS to show some styling and an actual img url for demo purpose only.
Live Working Demo:
let form = document.querySelector('#meme-form');
let img = document.querySelector('#img');
let topTxt = document.querySelector('#top-txt');
let bottomTxt = document.querySelector('#bottom-txt');
let results = document.querySelector('.meme-results');
form.addEventListener('submit', function(e) {
e.preventDefault();
let memePic = document.createElement('img');
var hrLine = document.createElement('hr');
//create the divs for the memes
let newDiv = document.createElement('div');
let topText = document.createElement('span');
let bttomText = document.createElement('span');
//Top text
topText.classList.add('top')
topText.textContent = topTxt.value
//Img
memePic.src = img.value;
results.appendChild(topText);
results.append(memePic);
//bottom text
bttomText.classList.add('bottom')
bttomText.textContent = bottomTxt.value
results.append(bttomText);
results.append(hrLine);
//set the textbox inputs equal to nothing
//img.value = '';
topTxt.value = '';
bottomTxt.value = '';
})
.meme-results {
width: 30%;
height: 300px;
margin: 10px;
display: block;
}
img {
width: 100%;
height: 100%;
display: block;
}
.top, #top-txt {
color: blue;
}
.bottom, #bottom-txt {
color: red;
}
<html>
<body>
<form action="" id="meme-form">
<label for="image">img url here</label>
<input id="img" type="url" value="https://via.placeholder.com/150"><br>
<label for="top-text">top text here</label>
<input id="top-txt" type="text"><br>
<label for="bottom-text">bottom text here</label>
<input id="bottom-txt" type="text"><br>
<input type="submit"><br>
</form>
<div class="meme-results"></div>
<script src="meme.js"></script>
</body>
</html>

add a button using javascript to an existing DIV

On my page I have:
<div id='something'></div>
and I want to append this type of 'button' to it using JS:
<span class="picon-p-add-news"></span>Read more news
I tried to use document.createElement but I'm not sure how to make it not just append it as text. How do I do this ?
Something like this, where you can pass your element ID and URL through function arguments.
<!DOCTYPE html>
<html>
<head>
<script>
function appendButton(elementId, url){
var buttonEl = document.createElement("a");
buttonEl.href = url;
var buttonTextEl = document.createElement("span");
buttonTextEl.className = "picon-p-add-news";
buttonTextEl.innerText = "Read more news";
buttonEl.appendChild(buttonTextEl);
document.getElementById(elementId).appendChild(buttonEl);
}
</script>
</head>
<body>
<div>
<button id="button">Click to add</button>
<div id='something'></div>
</div>
<script>
document.getElementById("button").addEventListener('click', () => appendButton("something", "/news_events/"));
</script>
</body>
</html>
Use document.createElement to create the specified HTML elements. Then you can append those to your #something root element using Node.appendChild function. You can also use Element.innerHTML to gets or sets the HTML markup contained within the element.
The Node.appendChild() method adds a node to the end of the list of children of a specified parent node.
const something = document.getElementById('something');
// creating the span element, then add a class attribute
const span = document.createElement('span');
span.setAttribute('class', 'picon-p-add-news');
span.innerHTML = 'span'; // some text to improve visualization
// create the anchor element with the href attribute
const a = document.createElement('a');
a.setAttribute('href', '/news_events/');
// append the span element inside the <a>
a.appendChild(span);
a.innerHTML += 'anchor'; // add extra text for display
// add the <a> element tree into the div#something
something.appendChild(a);
#something {
border: 1px solid;
text-align: center;
font-size: 2rem;
}
#something > a {
padding: 8px;
}
.picon-p-add-news {
background: red;
padding: 0 4px;
}
<div id="something"></div>
Like this? You can use the innerHTML attribute to add HTML inside of an Element
document.getElementById("something").innerHTML += '<span class="picon-p-add-news"></span>Read more news';
<div id='something'></div>
Or, if you created this as an Element with createElement, you can use appendChild:
let a = document.createElement("a");
a.setAttribute("href", "/news_events/");
let span = document.createElement("span");
span.setAttribute("class", "picon-p-add-news");
a.appendChild(span);
a.innerHTML += "Read more news";
document.getElementById("something2").appendChild(a);
<div id="something2"></div>
1) Create a element:
var aEl = document.createElement('a');
aEl.href = "/news_events/"
2) Create span element:
var spanEl = document.createElement('span');
spanEl.classList.add('picon-p-add-news');
3) Append span element to a element
aEl.appendChild(spanEl);
4) Insert text in a element
aEl.insertAdjacentText('beforeend','Read more news');
5) Append whole a tree to you div
var divEl = document.getElementById('something');
divEl.appendChild(aEl);
<html>
<head>
<style>
#myDIV {
border: 1px solid black;
margin-bottom: 10px;
}
</style>
</head>
<body>
<p>Click the button to create a P element with some text, and append it to DIV.</p>
<div id="myDIV">
A DIV element
</div>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var para = document.createElement("P");
var t = document.createTextNode("This is a paragraph.");
para.appendChild(t);
document.getElementById("myDIV").appendChild(para);
}
</script>
</body>
</html>
Give something like this a try: I used https://www.w3schools.com/jsref/met_document_createelement.asp for reference.

Javascript : add images in div upon selecting value from select box

I am trying too add image inside dynamically created div. When user create go button it should create div element and image inside it according to value selected in select box. I have created div tag dynamically and created image object in order to get image. but in my code image is not loading inside div. can anyone help me to figure out issue ?
CSS
<style>
body{
background-image: url("final_images/back.jpg");
}
.container{
/*width: 600px;*/
/*height: 200px;*/
border:inset;
margin-top: 100px;
margin-left: 300px;
margin-right: 190px;
background-color:rgba(255, 234, 134, 0.9);
}
#selectBox{
margin-left: 210px;
width: 160px;
}
#holder {
width: 300px;
height: 300px;
background-color: #ffffff;
}
</style>
HTML
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div class = 'container' id="main">
<form name="myForm">
<select name="mySelect" id="selectBox">
<option value="womens">Women's coat</option>
<option value="mens">Men's coat</option>
<option value="kids">Kid's toys</option>
<option value="mixture">Classic mixture</option>
<option value="earing">Gold Earing</option>
</select>
<INPUT TYPE="button" VALUE="Go" id="go">
</INPUT>
</form>
<HR size="4" color="red" id="hr">
<!-- <div id="holder"> </div> -->
</div>
</body>
</html>
Javascript
<script>
imageObj = new Image(128, 128);
// set image list
images = new Array();
images[0]="final_images/wcoat.jpg";
images[1]="final_images/wcoat.jpg";
var go = document.getElementById('go');
go.addEventListener("click", loadItem);
function loadItem() {
var mainDiv = document.getElementById("main");
var btnPre = document.createElement("input");
//Assign different attributes to the element.
btnPre.type = "button";
btnPre.value = "previous";
btnPre.id = "preBtn";
mainDiv.appendChild(btnPre);
newdiv = document.createElement('div'); //create a div
newdiv.id = 'holder';
mainDiv.appendChild(newdiv); //add an id
var btnNxt = document.createElement("input");
//Assign different attributes to the element.
btnNxt.type = "button";
btnNxt.value = "next";
btnNxt.id = "nxtBtn";
mainDiv.appendChild(btnNxt);
var holder = document.getElementById("holder");
if(document.getElementById('selectBox').value == "womens"){
holder.src = images[0] + " Women's coat";
}
else if(document.getElementById('selectBox').value == "mens"){
holder.src = images[1] + " Men's coat";
}
}
</script>
A div is not an image container. Replace with img in the createElement fixes this.
Another big problem is the margins you use.
I've made a few adjustments
replaced margin-left with float: right for the select
put margin auto for left and right on the box.
imageObj = new Image(128, 128);
// set image list
images = new Array();
images[0] = "final_images/wcoat.jpg";
images[1] = "final_images/wcoat.jpg";
var go = document.getElementById('go');
go.addEventListener("click", loadItem);
function loadItem() {
var mainDiv = document.getElementById("main");
var btnPre = document.createElement("input");
//Assign different attributes to the element.
btnPre.type = "button";
btnPre.value = "previous";
btnPre.id = "preBtn";
mainDiv.appendChild(btnPre);
newdiv = document.createElement('img'); //create a div
newdiv.id = 'holder';
mainDiv.appendChild(newdiv); //add an id
var btnNxt = document.createElement("input");
//Assign different attributes to the element.
btnNxt.type = "button";
btnNxt.value = "next";
btnNxt.id = "nxtBtn";
mainDiv.appendChild(btnNxt);
var holder = document.getElementById("holder");
if (document.getElementById('selectBox').value == "womens") {
holder.src = images[0] + " Women's coat";
} else if (document.getElementById('selectBox').value == "mens") {
holder.src = images[1] + " Men's coat";
}
}
body {
background-image: url("final_images/back.jpg");
}
* {
box-sizing: border-box;
}
.container {
width: 400px;
border: inset;
margin-top: 100px;
margin-left: auto;
margin-right: auto;
background-color: rgba(255, 234, 134, 0.9);
}
#selectBox {
float: right;
width: 160px;
}
#holder {
width: 300px;
height: 300px;
background-color: #ffffff;
}
<div class='container' id="main">
<form name="myForm">
<select name="mySelect" id="selectBox">
<option value="womens">Women's coat</option>
<option value="mens">Men's coat</option>
<option value="kids">Kid's toys</option>
<option value="mixture">Classic mixture</option>
<option value="earing">Gold Earing</option>
</select>
<INPUT TYPE="button" VALUE="Go" id="go">
</INPUT>
</form>
<HR size="4" color="red" id="hr" />
<!-- <div id="holder"> </div> -->
</div>
You need to use an image tag instead of a div. You could also load images with CSS but thats probably not what you want.
starting on this line:
var holder = document.getElementById("holder");
var image = new Image(128, 128);
if (document.getElementById('selectBox').value == "womens") {
image.src = images[0];
holder.appendChild(image);
holder.appendChild(document.createTextNode(" Women's coat"));
} else if (document.getElementById('selectBox').value == "mens") {
image.src = images[1];
holder.appendChild(image);
holder.appendChild(document.createTextNode(" Men's coat"));
}
Let me elaborate.
In the JavaScript code you are creating a div element here
newdiv = document.createElement('div'); //create a div
newdiv.id = 'holder';
mainDiv.appendChild(newdiv);
and then you are searching for element with Id holder and setting new image url.
var holder = document.getElementById("holder");
// holder is <div></div> element
if (document.getElementById('selectBox').value == "womens") {
holder.src = images[0] + " Women's coat";
} else if (document.getElementById('selectBox').value == "mens") {
holder.src = images[1] + " Men's coat";
}
holder is a div tag now. it has no src attribute
But div element do not have attribute with name src. so the above code will just add one more attribute to your div tag. but browser will not interpret it.
So if you want load image by setting src attribute, then you probably have to create holder as img tag which has attribute src. like this.
newdiv = document.createElement('img'); //create a img
newdiv.id = 'holder';
mainDiv.appendChild(newdiv);
holder is a img tag. now it has src attribute
now it will work with no problem.

Two div with same class name overlapping each other

On clicking a button my program will create a dynamic div with a class name dynamictextbox . There is a label with the class name mytxt and textbox with class name mytext inside this div which is also dynamically created.
When i create a new dynamic div it is overlapping with previously created div.
Below is the CSS i've used
.dynamictextbox{
width:50%;
position:relative;
padding:10;
}
.dynamictextbox .mytxt{
position:absolute;
left:0px;
right:50%;
}
.dynamictextbox .mytext{
position:absolute;
left:51%;
right:100%;
}
Below is the HTML code
<div id="Enter your name" class="dynamictextbox">
<label class="mytxt">Enter your name</label>
<input type="text" name="Enter your name_name" id="Enter your name_id" class="mytext">
</div>
<br />
<div id="bigData" class="dynamictextbox">
<label class="mytxt">Now this is a long text which will overlap the next div.Need solution for this. Please give me a solution for this</label>
<input type="text" name="bigData_name" id="bigDate_id" class="mytext">
</div>
<br />
<div id="div_temp" class="dynamictextbox">
<label id="txtlb" class="mytxt">Dynamic Label</label>
<input type="text" name="tb" id="tb" class="mytext">
</div>
<br />
What you need here, is to expand the element according to the content height. Unfortunately you cannot do this using CSS. So we'll have to move along with javascript.
Here goes the script
<script>
var max = 0;
function setHeight() {
var elements = document.getElementsByClassName('mytxt');
var height = 0;
for (var i = 0; i < elements.length; i++) {
height = elements[i].scrollHeight;
if (height > max) {
max = height;
}
}
elements = document.getElementsByClassName('dynamictextbox');
for (var i = 0; i < elements.length; i++) {
elements[i].style = "min-height: " + max + "px";
}
}
</script>
At the end of all the divs call the funtion setHeight().
<script>setHeight()</script>
So the output will look like this
P.S. I've added borders to the class dynamictextbox for testing purposes.
This may be helpful - JSFIDDLE
Just remove the .mytxt class from your CSS and increase the left attribute of .mytext class
.dynamictextbox .mytext{
position:absolute;
left:60%;
right:100%;
}
Update the code below. Is this what you where going after?
$("#add").on("click", function(){
// just a helper function for some random content
function dynamicText(){
var min = 1;
var max = 50;
var random = Math.floor(Math.random() * max) + min;
var text = "";
for(var i = 0; i < random; i++){
text += "text ";
}
return text;
}
// add to the container
var addMe = "\
<div class='dynamictextbox'>\
<label class='mytxt'>"+dynamicText()+"</label>\
<textarea class='mytext'>"+dynamicText()+"</textarea>\
</div>\
";
var container = $("#container");
container.append(addMe);
});
.dynamictextbox{
width:50%;
padding:10;
margin-top: 10px;
background: #CCC;
overflow: auto;
}
.dynamictextbox .mytxt{
position: relative;
float: left;
width: calc(50% - 10px);
}
.dynamictextbox .mytext{
float: right;
width: calc(50% - 10px);
height: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
On clicking a button my program will create a dynamic div with a class name dynamictextbox . There is a label with the class name mytxt and textbox with class name mytext inside this div which is also dynamically created.
<br><hr><br>
<button id="add">ADD</button><br><br>
<div id="container"></div>

Problem with innerXhtml and onclick attribute

In the XHTML page i have this div:
<div id="listAzioni">
<h4 style="margin-bottom:3px;">List shape :</h4>
</div>
Subsequently incorporated within the div an input element via javascript using the library innerXhtml.
var paper = document.getElementById("listAzioni");
var toWrite = "<h4 style=\"margin-bottom:3px\">List shape :</h4>";
toWrite += "<input type=\"button\" class=\"listButton\" value=\""+id+"\" onclick=\"showAction('"+id+"');\"/>"+'<br/>';
innerXHTML(paper,toWrite);
But after adding the input element has no onclick attribute. I tried so hard but I have not found anything that would solve my problem. Where am I doing wrong?
Which browsers have you tried?
I suggest you to use standard DOM APIs, I write your code as below:
<html>
<head>
<style type="text/css">
.button {
border: 1px solid black;
padding: 3px;
}
</style>
<script type='text/javascript'>
function addButton() {
var container = document.getElementById('container');
if (container != null && container != undefined) {
var child = document.createElement("div");
var button = document.createElement("input");
button.value = "Click to alert";
button.type = "button";
child.style.padding = "10px";
child.style.border = "2px solid red";
button.className = "button";
button.onclick = showAlert;
child.appendChild(button);
container.appendChild(child);
}
}
function showAlert() {
alert("you clicked the button!");
}
</script>
</head>
<body>
<div id="container"></div>
<input value="add div and button" type='button' onclick='addButton();'/>
</body>
</html>

Categories

Resources