Append div in button on click Javascript - javascript

Hi how to append div inside button on click this is my JavaScript:
function addLoader() {
var div = document.createElement('div');
div.innerHTML = '<div class="loader"> <div class="loader-ring"> <div class="loader-ring-light"></div> </div> </div>';
var test01 = document.createElement('button');
test01.appendChild(div);
console.log(test01);
}
I want to add innerHTML inside button tags on click
<button onclick="addLoader(this);">testt </button>
It must be like this when function is finish :
<button>testt <div class="loader"> <div class="loader-ring"> <div class="loader-ring-light"></div> </div> </div> </button>

HTML
// Added id attribute
<button onclick="addLoader();" id = "test01">testt </button>
JS
function addLoader() {
var _div = document.createElement('div');
_div.innerHTML = '<div class="loader"> <div class="loader-ring"> <div class="loader-ring-light"></div> </div> </div>';
//append _div to button
document.getElementById("test01").appendChild(_div);
}
Working jsfiddle
EDIT
This will append element to any button call addLoader on click
function addLoader(elem) {
var _div = document.createElement('div');
_div.innerHTML = '<div class="loader"> <div class="loader-ring"> <div class="loader-ring-light"></div> </div> </div>';
elem.appendChild(_div);
}
Updated jsfiddle

var btn = document.getElementById("addLoader");
if (btn) {
btn.addEventListener('click', addLoader, false);
}
function addLoader() {
var div = document.createElement('div');
div.innerHTML = '<div class="loader"> <div class="loader-ring"> <div class="loader-ring-light"></div> </div> </div>';
this.appendChild(div);
}
<button id="addLoader">Test</button>

You just need one more line of code. The variable test01 is created in memory but not added to the DOM. You must append this new element to the DOM (ie. document.appendChild(test01))

Related

How to create elements and delete them with native javascript without using jQuery

In the below link, there is a add more button, i want the add more to create the same input field with a delete button associated with it, but i would like to do it all with native js if possible.
https://codepen.io/aazim-khaki/pen/vYZmMRq
Current JS :
$(function() {
$(".btn-copy").on('click', function() {
var ele = $(this).closest('.example-2').clone(true);
ele.find('input').val('')
if (ele.find('button').length < 2) {
let btn = document.createElement("button");
btn.innerHTML = "Delete";
btn.onclick = (e) => {
e.preventDefault()
ele.remove()
}
ele[0].appendChild(btn);
}
$(this).closest('.example-2').after(ele);
})
})
Delegate
I moved the form tag and gave the button a delete class
window.addEventListener("load", function() {
document.querySelector(".row").addEventListener("click", function(e) {
const tgt = e.target;
if (tgt.classList.contains('delete')) {
tgt.closest('.example-2').remove()
} else if (tgt.classList.contains('btn-copy')) {
const ele = tgt.closest(".example-2").cloneNode(true);
ele.querySelector("input").value = "";
if (ele.querySelectorAll("button").length < 2) {
let btn = document.createElement("button");
btn.innerHTML = "Delete";
btn.classList.add("delete");
ele.appendChild(btn);
}
tgt.closest(".card-body").appendChild(ele)
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class="col-lg-12">
<div class="card">
<div class="card-header">
<h5 class="card-title">Add Class</h5>
</div>
<form action="#">
<div class="card-body">
<div class="example-2 form-group row">
<!--<label class="col-form-label col-md-2">Input Addons</label>-->
<div class="col-xs-2">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">Class Name</span>
</div>
<input class="form-control" type="text">
<div class="input-group-append">
<button class="btn-copy btn btn-primary" type="button">Add More</button>
</div>
</div>
</div>
</div>
<div class="form-group row">
<div class="col-xs-2">
<button class="btn btn-primary" type="button">Submit</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
Use a container and event delegation so you only use one listener rather than attaching a listener to each remove button.
This is a very simple example but the principles are the same.
// Cache your elements
const container = document.querySelector('#container');
const add = document.querySelector('button');
// Add your container an add button listeners
container.addEventListener('click', handleEvent, false);
add.addEventListener('click', handleAdd(), false);
// If a remove button is clicked, find the
// the closest div wrapper and remove it from
// the container
function handleEvent(e) {
const { id } = e.target.dataset;
const row = e.target.closest('.row');
container.removeChild(row);
}
// `handleAdd` returns a function (closure) that
// is used for the add listener rather than
// maintaining a global variable.
// We initialise the id at this point
function handleAdd(id = 0) {
// And now return the function that will be called
// when the add button is clicked
// For the purposes of this example it simply adds new HTML
// to the container, and then increases the id
return function() {
const html = `<div class="row"><input value="${id}" /><button data-id="${id}">Remove</button></div>`;
container.insertAdjacentHTML('beforeend', html);
++id;
}
}
<button>Add</button>
<div id="container"></div>

I want to dynamically create a tag by using javascript

I'm using a bootstrap modal.
The Function what I want to dynamically create a button at body tag when I click the modal button.
Description about function what I apply: As soon as I click the bluebutton, I want to create it at the body tag('beside the '+' button')
window.onlaod = function(){
var blue = document.getElementById('blue');
blue.onclick = function(){
blue.onclick = null;
var result = document.getElementById('result');
var newblue = document.createElement('span');
newblue.id = 'newblue';
newblue.innerHTML += '<button type="button" class="btn btn-primary btnWH " id="blue"></button>';
result.appendChild(newblue);
};
};
-> This is the code about event after click the bluebutton.
<!-- label color -->
<div class="modal-body">
<button type="button" class="btn btn-primary btnWH " id="blue"></button>
</div>
-> This is the code about bluebutton.
<div class="card border-secondary mb-3" style="max-width: 20rem;">
<div class="card-header">Header</div>
<div class="card-body">
<div id="result">
<span id="first">
<button type="button" class="btn btn-primary plusbtn" data-toggle="modal" data-target="#mymodal"> +
</button>
</span>
</div>
</div>
</div>
-> This is the code about '+'button.
This will create a button when click on add button inside div id of result code as follows:
<html>
<body>
<button type="button" id="blue">add</button>
<div id="result"></div>
<script>
window.onload = function() {
return addEvent();
}
function addEvent() {
var blueButton = document.getElementById('blue');
blueButton.addEventListener("click", addButton)
}
function addButton() {
var result = document.getElementById('result');
var newBtn = document.createElement('span');
newBtn.id = 'newblue';
newBtn.innerHTML += '<button type="button" id="blue">test</button>';
result.appendChild(newBtn);
}
</script>
</body>
</html>

insert content into div from textarea Javascript

I am building a chat and i need to append content from the textarea to an inner div upon clicking send
<div class="inner" id="inner">
<div class="incoming" id="incoming">
<div class="them" id="them">Lorem
</div>
</div>
<div class="outgoing" id="outgoing">
<div class="me" id="me">Lorem ipsum
</div>
</div>
</div>
the button and textarea code is
<textarea class="input" id="input" placeholder="Message.."></textarea>
<a class="waves-effect waves-light" id="send-btn" >Send</a>
Javascript
var sendButton= document.getElementById('send-btn');
var textArea = document.getElementById('input');
var innerDiv= document.getElementById('inner');
var message=textArea.value;
sendButton.addEventListener('click', function(){
innerDiv.innerHTML=meMessage;
});
var meMessage= '<div class="outgoing" id="outgoing">'+
'<div class="me" id="me"></div></div>';
What i am trying to do is show the text value of the text area to the inner div called 'me' when i click send
and also get the value of the textarea to save it to a database. How can i achieve this
First of all you shouldn't create html elements manually since they would be XSS vulnerable and read about escaping mechanics to prevent malicious code being injected.
Try using document.createElement('div'); method to create div with valid innerText.
later use method:
innerDiv.appendChild(createdElement);
To append element.
You could create builder to build html elements you need and you have to htmlEncode text that will be inside of div element.
const sendButton = document.getElementById('send-btn');
const textArea = document.getElementById('input');
const innerDiv = document.getElementById('inner');
var message = textArea.value;
sendButton.addEventListener('click', function () {
const message = new MessageContainerBuilder().BuildMessage(textArea.value);
innerDiv.appendChild(message);
textArea.value = '';
});
function encodeHtmlEntity(input) {
var output = input.replace(/[\u00A0-\u9999<>\&]/gim, function (i) {
return '&#' + i.charCodeAt(0) + ';';
});
return output;
}
function MessageContainerBuilder() {
var createDivElement = function (classTest) {
var div = document.createElement('div');
var classAttr = document.createAttribute('class');
classAttr.value = classTest;
div.setAttributeNode(classAttr);
return div;
};
var createSpanElement = function (value, classTest) {
var span = document.createElement('span');
if (classTest) {
var classAttr = document.createAttribute('class');
classAttr.value = classTest;
span.setAttributeNode(classAttr);
}
span.innerText = encodeHtmlEntity(value);
return span;
};
this.BuildMessage = function (text) {
var divContainer = createDivElement('outgoing');
var messageSpan = createSpanElement(text, 'me');
divContainer.appendChild(messageSpan);
return divContainer;
};
}
<div id="inner">
<div class="incoming">
<div class="them">Lorem
</div>
</div>
<div class="outgoing">
<div class="me">Lorem ipsum
</div>
</div>
</div>
<textarea class="input" id="input" placeholder="Message..."></textarea>
<button class="waves-effect waves-light" id="send-btn">Send</button>
UPDATE: Extended snippet code. Removed Ids since they shouldn't be used there to create multiple message elements with same Id. Changed anchor to button.
You need to get the value of the textarea on click of the link
var sendButton = document.getElementById('send-btn');
var textArea = document.getElementById('input');
var innerDiv = document.getElementById('inner');
var message = textArea.value;
sendButton.addEventListener('click', function() {
innerDiv.innerHTML = `<div class="outgoing" id="outgoing">${textArea.value}
<div class="me" id="me"></div></div>`;
});
<div class="inner" id="inner">
<div class="incoming" id="incoming">
<div class="them" id="them">Lorem
</div>
</div>
<div class="outgoing" id="outgoing">
<div class="me" id="me">Lorem ipsum
</div>
</div>
</div>
<textarea class="input" id="input" placeholder="Message.."></textarea>
<a class="waves-effect waves-light" id="send-btn">Send</a>
You can use this. Youe message variable is not receiving the textarea value
var sendButton= document.getElementById('send-btn');
var innerDiv= document.getElementById('inner');
sendButton.addEventListener('click', function(){
innerDiv.innerHTML=innerDiv.innerHTML+'<div class="outgoing" id="outgoing">'+document.getElementById('input').value+
'<div class="me" id="me"></div></div>';
});
<div class="inner" id="inner">
<div class="incoming" id="incoming">
<div class="them" id="them">Lorem
</div>
</div>
<div class="outgoing" id="outgoing">
<div class="me" id="me">Lorem ipsum
</div>
</div>
</div>
<textarea class="input" id="input" placeholder="Message.."></textarea>
<a class="waves-effect waves-light" id="send-btn" >Send</a>
Maybe be replacing your js with that :
document.getElementById('send-btn').addEventListener('click',
function(){
var userInput = document.getElementById('input').value;
if(userInput) { document.getElementById('me').innerHTML += '<br>' + userInput; }
}
);
That should let you go a step forward... And good luck for saving to DB.
innerDiv.append(message)
instead of
innerDiv.innerHTML=message

Create a html element and find a div by id before adding in DOM

I'm trying to find a the div with id old-price and remove it, before inserting in the document ( before main.appendChild(newDiv);).
p.s.: Can't use JQuery
I already tried this:
newDiv.getElementById("old-price").innerHTML = "";
but it does not work
Any help will be appreciated.
var divString = "<div class='col-xs-12 col-sm-6 col-md-4 col-lg-4'> <div class='thumbnail'> <h1 class='text-center'> Black Shoes with red stripes </h1> <img src='img/02.jpg'> <small id='old-price' class='old-price'>250</small> <p class='price'>250</p> <a class='btn btn-primary'>BUY</a> </div> </div> ";
var newDiv = document.createElement('div');
newDiv.innerHTML = divString;
//remove the div with id old-price
var main = document.getElementById("main");
main.appendChild(newDiv);
<div id="main">
</div>
use newDiv.querySelector("#old-price").remove().
var divString = "<div class='col-xs-12 col-sm-6 col-md-4 col-lg-4'> <div class='thumbnail'> <h1 class='text-center'> Black Shoes with red stripes </h1> <img src='img/02.jpg'> <small id='old-price' class='old-price'>250</small> <p class='price'>250</p> <a class='btn btn-primary'>BUY</a> </div> </div> ";
var newDiv = document.createElement('div');
newDiv.innerHTML = divString;
//remove the div with id old-price
newDiv.querySelector("#old-price").remove()
var main = document.getElementById("main");
main.appendChild(newDiv);
<div id="main">
</div>
Try this:
var divString = "<div class='col-xs-12 col-sm-6 col-md-4 col-lg-4'> <div class='thumbnail'> <h1 class='text-center'> Black Shoes with red stripes </h1> <img src='img/02.jpg'> <small id='old-price' class='old-price'>250</small> <p class='price'>250</p> <a class='btn btn-primary'>BUY</a> </div> </div> ";
var newDiv = document.createElement('div');
newDiv.innerHTML = divString;
//remove the old price
newDiv.getElementsByClassName("old-price")[0].innerHTML="";
var main = document.getElementById("main");
main.appendChild(newDiv);
You can try to hide it by this:
document.getElementById("old-price").style.display = 'none';
Or remove it as child from parent element (replace parent ID):
document.getElementById("parentID").removeChild("old-price");

how to create generic html with javascript

I have the following html:
<div id="prog" class="downloads clearfix">
<div class="item">
<div class="image_container">
<img src="/img/downloads/company.png" width="168" height="238" alt="">
</div>
<div class="title">
pricelist: <label id="pr1"></label>
</div>
<div class="type">
pdf document
</div>
<div class="link">
<a id="pdfdocument" class="button" target="_blank" href="#">start Download </a>
</div>
</div>
</div>
I want build HTML which is inside the <div id="prog"> with Javascript:
<div id="prog" class="downloads clearfix"></div>
I'm trying to use this Javascript, but without success:
var tmpDocument, tmpAnchorTagPdf, tmpAnchorTagXls, parentContainer, i;
parentContainer = document.getElementById('prog');
for (i = 0; i < documents.length; i++) {
tmpDocument = documents[i];
tmpAnchorTagPdf = document.createElement('a id="pdfdocument" ');
tmpAnchorTagPdf.href = '/role?element=' + contentElement.id + '&handle=' + ope.handle;
tmpAnchorTagPdf.innerHTML = 'start Download';
tmpAnchorTagXls = document.createElement('a');
tmpAnchorTagXls.href = '/role?element=' + contentElement.id + '&handle=' + ope.handle;
tmpAnchorTagXls.innerHTML = 'start Download';
parentContainer.appendChild(tmpAnchorTagPdf);
parentContainer.appendChild(tmpAnchorTagXls);
}
If this is a section of code that you will be using more than once, you could take the following approach.
Here is the original div without the code you want to create:
<div id="prog" class="downloads clearfix">
</div>
Create a template in a hidden div like:
<div id="itemtemplate" style="display: none;">
<div class="item">
<div class="image_container">
<img src="/img/downloads/company.png" width="168" height="238" alt="">
</div>
<div class="title">
pricelist: <label></label>
</div>
<div class="type">
pdf document
</div>
<div class="link">
<a class="button" target="_blank" href="#">start Download </a>
</div>
</div>
</div>
Then duplicate it with jquery (OP originally had a jquery tag; see below for JS), update some HTML in the duplicated div, then add it to the document
function addItem() {
var item = $("#itemtemplate div.item").clone();
//then you can search inside the item
//let's set the id of the "a" back to what it was in your example
item.find("div.link a").attr("id", "pdfdocument");
//...the id of the label
item.find("div.title label").attr("id", "pr1");
//then add the objects to the #prog div
$("#prog").append(item);
}
update
Here is the same addItem() function for this example using pure Javascript:
function JSaddItem() {
//get the template
var template = document.getElementById("itemtemplate");
//get the starting item
var tempitem = template.firstChild;
while(tempitem != null && tempitem.nodeName != "DIV") {
tempitem = tempitem.nextSibling;
}
if (tempitem == null) return;
//clone the item
var item = tempitem.cloneNode(true);
//update the id of the link
var a = item.querySelector(".link > a");
a.id = "pdfdocument";
//update the id of the label
var l = item.querySelector(".title > label");
l.id = "pr1";
//get the prog div
var prog = document.getElementById("prog");
//append the new div
prog.appendChild(item);
}
I put together a JSFiddle with both approaches here.

Categories