How to add Elements to DOM - javascript

I need a function which creates element and than adds text to that element and than adds that new element to a some location in DOM. I am noob to this.
I find this function but I don't know how to automaticaly specify location so that I can just call function and for example specify third argument as an element to which I want to append new element.
function appendElement (elemNode,textNode) {
var element = document.createElement(elemNode);
var text = document.createTextNode(textNode);
element.appendChild(text);
document.body.appendChild(element);
}
appendElement("b","lorem");

function appendElement (elemNode,textNode,containerToAppend) {
var container = document.getElementById(containerToAppend);
var element = document.createElement(elemNode);
var text = document.createTextNode(textNode);
element.appendChild(text);
container.appendChild(element);
}
appendElement("b","lorem","ContainerId");

Here's a way to do it in one line:
function appendElement (elemNode, textContent, parent) {
parent.appendChild(document.createElement(elemNode)).textContent = textContent;
}
appendElement("b","lorem", document.getElementById("container"));
div { background-color: aqua }
<div id="container"></div>

function appendElement (elemNode,textNode,containerToAppend) {
var container = document.getElementById(containerToAppend);
var element = document.createElement(elemNode);
var text = document.createTextNode(textNode);
element.appendChild(text);
container.appendChild(element);
}
appendElement("p","this is text","ContainerId");

Here is my attempt. Completely ripped off from developer.Mozilla.org with a minor tweak.
JSFIDDLE DEMO
Javascript:
function addElement() {
// Create a new div element and give it some content
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.
// Add the newly created element and its content into the Parent of the clicked button
var parentDiv = event.target.parentNode;
document.body.insertBefore(newDiv, parentDiv);
}
HTML
<div id="div1">
<input type="button" onclick="addElement(event)" value="Click me to add div" />
</div>
<div id="div2">
<input type="button" onclick="addElement(event)" value="Click me to add div" />
</div>
<div id="div3">
<input type="button" onclick="addElement(event)" value="Click me to add div" />
</div>

Related

How to delete text box along with button in JavaScript

I have a button when user clicks the button it create the text box along with remove button
but all the text boxes created with same id how we can delete the text box when clicks respective remove button
here My Code:
<body>
<button type="button" id="URLbtn" onclick="Createinput()"> + Add URL</button>
<div id="TextAreaBtn"></div>
<script>
function Createinput() {
var newdiv=document.createElement("div");
newdiv.id="test"
var Inputele=document.createElement("input");
Inputele.type="text";
Inputele.id="URLtxt"
newdiv.appendChild(btnele);
var btnele=document.createElement("button");
btnele.id="rmvbtn"
btnele.type="button"
btnele.innerHTML="-"
btnele.onclick=RemoveUrlBox()
newdiv.appendChild(btnele);
var element = document.getElementById("TextAreaBtn");
element.appendChild(newdiv);
}
function RemoveUrlBox() {}
</script>
</body>
i am getting following output
if user click 2 remove button only remove the second textbox and button
You need to select the wrapping div. Easiest way is to use remove() and use closest. No need to use the id..... You also need to remember ids need to be unique.
function createInput() {
var newDiv = document.createElement("div");
newDiv.className = 'group';
var inputElem = document.createElement("input");
inputElem.type = "text";
newDiv.appendChild(inputElem);
var btnElem = document.createElement("button");
btnElem.type = "button";
btnElem.textContent = "-";
btnElem.addEventListener("click", removeUrlBox);
newDiv.appendChild(btnElem);
var element = document.getElementById("TextAreaBtn");
element.appendChild(newDiv);
}
function removeUrlBox() {
this.closest('.group').remove();
}
<button type="button" id="URLbtn" onclick="createInput()"> + Add URL</button>
<div id="TextAreaBtn"></div>
This should do the trick:
const txtarea=document.getElementById('TextAreaBtn');
document.getElementById('URLbtn').onclick=()=>txtarea.innerHTML+=
'<div><input type="text" class="URLtxt"><button class="rmvbtn">-</button></div>';
txtarea.onclick=ev=>ev.target.className==="rmvbtn"&&ev.target.parentNode.remove()
<button type="button" id="URLbtn"> + Add URL</button>
<div id="TextAreaBtn"></div>
I replaced your id attributes with class attributes, as these don't need to be unique.
I reduced your script by using innerHTML instead of laboriously putting elements together with createElement(). This is a matter of opinion as both methods have their advantages.
I also used delegated event listener attachment for the removal buttons. This way you can get away with a single event listener on div.TextAreaBtn. The attached funcion will only trigger any action if the clicked element has class "rmvbtn".
Change
btnele.onclick=RemoveUrlBox()
to
btnele.addEventListener('click', function (e) {
// `this` is the button that was clicked no matter about the id
// `this.parentNode` is the div you want to remove
const nodeToRemove = this.parentNode;
nodeToRemove.parentNode.removeChild(nodeToRemove);
});

Clicking a button to update text in JavaScript

<div id="div1"></div>
<button id="addText" onclick="addText()">Add Text</button><br>
I'm trying to have this button call this function to update a text field. I don't want it to go to an action page or anything. The display aspect isn't even important. I'm just trying to find out how to update a variable in the background with a button click.
function addText(){
// create a new div element
var newDiv = document.createElement("div");
// and give it some content
var newContent = document.createTextNode("Hi there and greetings!");
// add the text node to the newly created div
newDiv.appendChild(newContent);
// add the newly created element and its content into the DOM
var currentDiv = document.getElementById("div1");
document.body.insertBefore(newDiv, currentDiv);
}
Try this
function addText(){
document.getElementById("div1").innerHTML = "your change text";
}

Whole div is replaced while trying to replace an element

I want to replace an element by another.
The element however is placed in an div with other elements.
When I run my code the whole div is replaced.
How do I prevent this behavior?
function edit(e) {
selectedElement = e.id
var newElement = document.createElement("input");
var newElementA = document.createTextNode("bla");
newElement.appendChild(newElementA);
var oldElement = document.getElementById(selectedElement);
var parentDiv = oldElement.parentNode
parentDiv.replaceChild(newElement, oldElement);
}
You shouldn't be appending a text node to an input box. You should set the value.
Here is a working codepen, based on your comments.
<div id="parentDiv">
<div>
hi
</div>
<a id="pleaseReplace" onclick="edit(event)">hi2</a>
<div>
hi3
</div>
</div>
function edit(e) {
selectedElement = document.getElementById(e.srcElement.id);
var newElement = document.createElement("input");
newElement.value = selectedElement.innerHTML;
var parentDiv = selectedElement.parentNode
selectedElement = parentDiv.replaceChild(newElement, selectedElement);
}

Javascript Function to Remove Div

I need a function that can delete the div one by one .
My code is shown below. in my code i have created a function to create a div when i click a button . and i can't figure how to delete div one by one .
Please help me with the correct code to delete div one by one.
<html>
<head>
</head>
<body>
<button id="buttonone" onclick="creatediv()">CREATE A DIV</button>
<button id="buttontwo" onlick="removedivider()">Remove DIV </button>
<script>
function creatediv()
{
document.getElementById("buttonone").innerHTML="CREATE ANOTHER DIV";
var newdiv = document.createElement("div");
newdiv.setAttribute("id","newdiv");
var text = document.createTextNode(Math.floor(Math.random()*100)+1);
newdiv.appendChild(text);
newdiv.style.color="white";
newdiv.style.width="100px";
newdiv.style.backgroundColor="green";
document.body.appendChild(newdiv);
}
function removedivider()
{
//Function to Remove the DIV one by one;
}
</script>
</body>
</html>
<script>
var index = 0;
function creatediv()
{
++index;
document.getElementById("buttonone").innerHTML="CREATE ANOTHER DIV";
var newdiv = document.createElement("span");
newdiv.setAttribute("id","newdiv" + index);
var text = document.createTextNode(Math.floor(Math.random()*100)+1);
newdiv.appendChild(text);
newdiv.style.color="white";
newdiv.style.width="100px";
newdiv.style.backgroundColor="green";
document.body.appendChild(newdiv);
}
function removedivider()
{
document.body.removeChild(document.getElementById("newdiv" + index));
--index;
}
</script>
Should work, I didn't test.
You weren't very clear regarding which div should be removed. Also, in your code, you repeatedly appended divs with the same id. You can't do that.
I made a quick example that removes the div appended first (a queue). I gave each date an id based on the current time, but such isn't really necessary. You could always just remove the first child of the parent div to which you are appending these divs.
However, if you plan on appending these divs in places that are not necessarily all under the same parent, then giving them unique ids and storing said ids is useful.
fiddle
HTML
<button id="add">add</button>
<button id="remove">remove</button>
<div id="holder">
<p>Added divs will go here</p>
</div>
JavaScript
var ids = [];
document.getElementById("add").onclick = function () {
var id = new Date().getTime(), // generate unique id (sort of)
div = document.createElement("div"); // create a div element
ids.push(id); // push the generated id to the holder array, ids
div.appendChild(document.createTextNode(id)); // append a text node to the div
div.setAttribute("class", "newDiv"); // give it a class for styling
div.setAttribute("id", id); // set its id
document.getElementById("holder").appendChild(div); // append the div
}
document.getElementById("remove").onclick = function () {
if (ids.length) { // only perform if a div has been appended
var div = document.getElementById(ids.shift());
// ids.shift() removes and returns ids[0], or the earliest added div
// this finds that element in the DOM
div.parentNode.removeChild(div); // and removes it
} else { // otherwise alert that there are no divs to remove
alert("no divs to remove!");
}
}
CSS
.newDiv {
height: 20px;
width: 110px;
background-color: #7EA8CA;
border: solid 1px #93CC76;
}
Replace your code with the following
<!DOCTYPE html>
<html>
<head>
<title>DIVs</title>
<script type="text/javascript">
function create_div() {
document.getElementById("button1").innerHTML="CREATE ANOTHER DIV";
var div = document.createElement("DIV");
var text = document.createTextNode(Math.floor(Math.random()*100)+1);
div.appendChild(text);
div.style.color = "white";
div.style.width = "100px";
div.style.backgroundColor = "green";
document.body.appendChild(div);
}
function remove_div() {
var div = document.getElementsByTagName('DIV'), i;
for(i = div.length-1; i >= 0; i--){
div[i].parentNode.removeChild(div[i]);
return false;
}
}
</script>
</head>
<body>
<button id="button1" onclick="create_div()">CREATE DIV</button>
<button id="button2" onclick="remove_div()">REMOVE DIV</button>
</body>
</html>
By the way, you can't have multiple DIVs having the same ID. Check the working jsBin
This function assumes there will be no other div elements. It will also remove the divs in fifo order.
function removedivider() {
var divs = document.getElementsByTagName('div');
if (divs.length > 0) divs[0].remove();
}
EDIT:
Here's a jsfiddle

How to dynamically change html elements and copy attributes with javascript

How can you change the hyrarchy / structure of html when it's rendered with javascript?
I would like to remove a parent div and copy it's attribute and classname
to it's child element. But I want to do this in the whole page that contains a certain class name.
In code example: I need this code
<div class="abc" myid="123" position="2">
<div class="someblock">
<p>Some paragraph</p>
<img width="140px; height: 140px; class="myimg" src="url to imgage">
</div>
changed to :
<div class="someblock" class="abc" myid="123" position="2">
<p>Some paragraph</p>
<img width="140px; height: 140px; class="myimg" src="url to imgage" />
</div>
Does anyone know how this can be done with JavaScript, or jQuery?
Thanks in advance!,
Chris.
You can try:
<script>
$('.abc').each(function(){
$(this).children().addClass($(this).attr('class'));
$(this).children().attr('myid', $(this).attr('myid'));
$(this).children().attr('position', $(this).attr('position'));
$('body').append($(this).html());
$(this).remove();
});
</script>
Be careful.
$('.someblock').each(function () {
var pt = $(this).parent(),
cl = pt.attr('class'),
id = pt.attr('id'),
pos = pt.attr('position');
$(this).unwrap().attr({id:id, position:pos}).addClass(cl);
});
May be something like this could help:
function deleteParent(id){
var element = document.getElementById(id);
var parent = element.parentNode;
var grandParent = parent.parentNode;
var html = parent.innerHTML;
grandParent.removeChild(parent);
grandParent.innerHTML += html;
}
$('.abc .someblock').contents().unwrap().parent().addClass('someblock');
Demo ---> http://jsfiddle.net/VQRQV/1/
var el = document.getElementById('123');
if(el) {
el.className += el.className ? ' someblock' : 'abc';
}
You can do this first by getting all the elements as
var allElem = document.getElementByID ("*");
then loop through all the elements.
To get to child element check whether a element has children find the last child and a get attribute value example:
var elemVal = allElem[i].className ; or allElem[i].getAttribute("xyx")
and then put the value of this element to desired element in html.
document.getElementById("div").className = elemVal ;

Categories

Resources