Delete a div using "this" with Javascript - javascript

What I would like to do is to create a div by clicking on a button. In that div there will be another button if clicked will delete the div that it is in. So potentially the first button will create many div's with this delete button inside but I want the delete button to only delete the div that it is within. Any suggestions?

If you do not need to keep the "delete button" on your page, bind the click event on each of them and use .removeChild on the parent element of the parent div.
FIDDLE DEMO

You can do something like:
<script>
var addDiv = (function() {
var div = document.createElement('div');
div.appendChild(document.createTextNode('some text'));
var button = document.createElement('button');
button.appendChild(document.createTextNode('Remove...'));
button.type = "button";
return function() {
var d = div.cloneNode(true);
var b = button.cloneNode(true);
b.onclick = function() {
var d = this.parentNode;
d.parentNode.removeChild(d);
};
d.appendChild(b);
document.body.appendChild(d);
};
}())
</script>
<button onclick="addDiv()">Add a div</button>
The above is just a trivial example to demonstrate one way to go about it. Note that if you clone an element, listeners added as properties or by addEventListener are dropped (this script would be very much simpler if they weren't).

HTML:
<input type="button" id='create' value="Create div!"/>
JS:
var i = 0;
document.onclick = function(e) {
var t = e.target;
if(t.id == 'create'){
t.parentNode.innerHTML += '<div>I AM A CHILD '+(++i)+' <input type="button" class="child" value="DELETE ME!"/><br/></div>';
}
if (t.className == 'child') {
t.parentNode.outerHTML = '';
}
};
using document.onclick and detecting the target element can be used as a live click to monitor newly created divs.
Its early and my brain may be a little foggy and the code may be a little dirty
Here is a jsfiddle

Related

Create multiple elements and delete a single one JavaScript

I'm working on a JavaScript project where a user can click a button to create a text element. However, I also want a feature where I can click a different button and the element that was created most recently will be removed, so In other words, I want to be able to click a button to create an element and click a different button to undo that action.
The problem I was having was that I created the element, then I would remove the element using:
element.parentNode.removeChild(element); , but it would clear all of the elements that were created under the same variable.
var elem = document.createElement("div");
elem.innerText = "Text";
document.body.appendChild(elem);
This code allows an element to be created with a button click. All elemente that would be created are under the "elem" variable. so when I remove the element "elem", all element are cleared.
Is there a simple way to remove on element at a time that were all created procedurally?
Thanks for any help
When you create the elements, give the a class. When you want to remove an element, just get the last element by the className and remove it.
The below snippet demonstrates it -
for(let i = 0; i<5; i++){
var elem = document.createElement("div");
elem.innerText = "Text " + i;
elem.className = "added";
document.body.appendChild(elem);
}
setTimeout(function(){
var allDivs = document.getElementsByClassName("added");
var lastDiv = allDivs.length-1;
document.body.removeChild(allDivs[lastDiv]);
}, 3000);
I would probably use querySelectors to grab the last element:
// optional
// this is not needed it's just a random string added as
// content so we can see that the last one is removed
function uid() {
return Math.random().toString(36).slice(2);
}
document.querySelector('#add')
.addEventListener('click', (e) => {
const elem = document.createElement('div');
elem.textContent = `Text #${uid()}`;
document.querySelector('#container').appendChild(elem);
// optional - if there are elements to remove,
// enable the undo button
document.querySelector('#undo').removeAttribute('disabled');
});
document.querySelector('#undo')
.addEventListener('click', (e) => {
// grab the last child and remove
document.querySelector('#container > div:last-child').remove();
// optional - if there are no more divs we disable the undo button
if (document.querySelectorAll('#container > div').length === 0) {
document.querySelector('#undo').setAttribute('disabled', '');
}
});
<button id="add">Add</button>
<button id="undo" disabled>Undo</button>
<div id="container"></div>

Duplicate a div with a Bootstrap button

I've been messing around with this for a couple of hours now, but for the life of me, cannot seem to get it to work, so any help greatly appreciated.
For context, I have a page which has a bootstrap form contained within it, the form contains divs which contain the form elements. There are 5 divs and the page by default, but I have a button, that when clicked I want to duplicate and continue to add as many additional "lines" to the form as the user would like.
This is the code I have in the button itself, within the bootstrap html doc:
<button style="margin-top:30px" id="button" onclick="duplicate()">ADD NEW LINE</button>
And this is the javascript that I have:
document.getElementById('button').onclick = duplicate;
var i = 0;
var original = document.getElementById('duplicater');
function duplicate() {
var clone = original.cloneNode(true); // "deep" clone
clone.id = "duplicater" + ++i; // there can only be one element with an ID
original.parentNode.appendChild(clone);
}
The Javascript file is physically located (locally at present) at /js/addnewline.js
And I have it referenced at the bottom of the HTML page like this:
<script src="/js/addnewline.js"></script>
When loading up the page and clicking the button, nothing happens.
Any pointers are welcomed.
Thank you in advance,
Gavin
you have a wrong id in you button. you have id="button" instead of id="duplicater"
this is your solution:
<button style="margin-top:30px" id="duplicater" onclick="duplicate()">ADD NEW LINE</button>
The problem is in this line " document.getElementById('button').onclick = duplicate;" here you have defined the click event but at the same time you have used onclick inside the button remove this " document.getElementById('button').onclick = duplicate;" line and the id of the button should be duplicater
<button style="margin-top:30px" id="duplicater" onclick="duplicate()">ADD NEW LINE</button>
var i = 0;
var original = document.getElementById('duplicater');
console.log(original)
function duplicate() {
console.log(original)
var clone = original.cloneNode(true); // "deep" clone
clone.id = "duplicater" + ++i; // there can only be one element with an ID
original.parentNode.appendChild(clone);
}

How to add a function on an element that was made after DOM creation?

I have a function that creates an html element with an unique ID.
And after that I want that when I click this element I could call a new function.
Quick example:
1) I click a button "Create element";
2) An element is created with id of "New_Element";
3) I click the "New_Element";
4) I get a function that was already preset to this element.
My current code for creating an element.
var pageRows = document.getElementsByClassName('pageRows');
var pageRowID = "section";
var el = document.createElement('section');
el.setAttribute('id', pageRowID + pageRows.length);
var row = document.getElementById('allNewRows');
row.parentNode.appendChild(el);
el.innerText = "New " + pageRows.length + " ROW!";
Now that the Element of id "pageRowId0" is created I want to have a function that works when I click this element.
Best wishes.
Thanks for helping.
You can do element.onclick= function(){}
var pageRows = document.getElementsByClassName('pageRows');
var pageRowID = "section";
var el = document.createElement('section');
el.setAttribute('id', pageRowID + pageRows.length);
el.onclick = function(){
/*write your fn here*/
};
var row = document.getElementById('allNewRows');
row.parentNode.appendChild(el);
el.innerText = "New " + pageRows.length + " ROW!";
You can use event delegation:
var row = document.getElementById('allNewRows');
row.parentNode.onclick = function(e) {
if (e.target.nodeName.toLowerCase() == 'select') {
//click on target select element
}
};
The snippet below has two parts. The first piece of code allows you to add a bunch of elements with different texts to the document.
The second parts shows the text of the element you clicked.
You will notice that the click event handler is just assigned to the parent element in which the new elements are added. No explicit click event handlers are bound to the new element.
I like to use addEventListener, because I think it's better to add a listener for a specific goal than to override any other event listeners by bluntly setting 'onclick', but that's a matter of opinion.
// Only run this code when the DOM is loaded, so we can be sure the proper elements exist.
window.addEventListener('DOMContentLoaded', function(){
// The code to add an element when the add button was clicked.
document.getElementById('add').addEventListener('click', function() {
var element = document.createElement('div');
element.innerText = document.getElementById('text').value;
element.className = 'clickableElement';
document.getElementById('elements').appendChild(element);
});
// Click event handler for the 'elements' div and everything in it.
document.getElementById('elements').addEventListener('click', function(event) {
var target = event.target; // The element that was clicked
// Check if the clicked element is indeed the right one.
if (target.classList.contains('clickableElement')) {
alert(target.innerText);
}
});
})
<input id="text" value="test"><button id="add">add</button>
<div id="elements"></div>

Javascript only last event listener works

It's very difficult for me to show you my code, as it's all over the place, but what I'm trying to do is this:
I am injecting html code into the DOM in a function buy using .innerHTML, I wish to add a click event to an icon that is being injected in this step, as at this moment in time I know its id. So after I've injected it I write:
document.getElementById(product.id+"x").addEventListener("click", removeItem);
product.id is created above and this element is a 'X' button, that when clicked will be removed from the screen.
The trouble is, this code is run many times as there are many items to be displayed on the screen. And when finished, only the last even made fires when the 'X' button is pressed.
Any suggestions?
EDIT:
I am unable to use jquery in this project.
Here is my code:
function createHTML(targetID, product) {
var target = document.getElementById(targetID);
total = (parseFloat(total) + parseFloat(product.price)).toFixed(2);;
target.innerHTML += '<article class="item" id="'+product.id+'"><img class="item_img" src="../'+product.image+'" width=100 height=100><h1 class="item_name">'+product.name+'</h1><p class="item_description">'+product.desc+'</p><h1 class="item_quantity">Quantity: '+product.quantity+'</h1><h1 class="item_price">£'+product.price+'</h1><i id="'+product.id+'x" class="fa fa-times"></i></article>';
document.getElementById(product.id+"x").addEventListener("click", removeItem, true);
}
So you're adding new elements to a container by overwriting the innerHTML or appending to it using +=. This is your problem. When you overwrite the innerHTML or append to it, you are destroying and recreating all elements within it and this causes them to lose any bound event handlers (ie your click handler).
This fiddle reproduces your problem. Only the last button has a click handler.
The solution is to build DOM elements using document.createElement() and use appendChild() or similar to append them, instead of creating/appending raw HTML. This way, your previous elements event handlers will remain intact.
This Fiddle uses DOM nodes instead of raw HTML and all buttons have a click handler.
Example fix:
var container = document.getElementById("container");
var elem;
function clicky(){
alert("clicked");
}
for(var i=0; i<4; i++){
elem = document.createElement('button');
elem.id = "btn_" + i;
elem.appendChild(document.createTextNode('Click'));
elem.addEventListener("click", clicky);
container.appendChild(elem);
}
I quess you do something like that
//Place where you add elements.
var container = document.body;
you create element and add listener to that element(button):
var button = '<button id="btn1x">Button 1</button>';
container.innerHTML += button;
//product.id = 'btn1';
document.getElementById(product.id+"x").addEventListener("click", removeItem);
and then you add in the same way new elements and add for them event listeners before next element will be generated.
If my quess is right, then your problem is that you replace whole content of container so previous event listens are lost.
stringVariable += 'abc' is the same as stringVariable = stringVariable + 'abc'. Because of that you overwrite html.
You should create elements from functions, not from string as you do now.
var button = document.createElement('button');
button.id = product.id + 'x';
button.innerText = 'Button 1'; // Title of button.
//Add button to container.
container.appendChild(button);
//Add event listener to created button.
button.addEventListener('click', myFunc);
UPDATE:
There are a way to parse your string to element.
First create container where will be set inner html from string, then get from that temp container first element (or more elements, depends from your html string), then add them to container and add to these elements listeners.
DEMO: http://jsfiddle.net/3cD4G/1/
HTML:
<div id="container">
</div>
Javascript:
var container = document.getElementById("container");
function clicky(){
alert("clicked");
}
var tempContainer = document.createElement('div');
for(var i=0; i<4; i++){
//Create your element as string.
var strElem = "<button type='button' id='btn_" + i + "'>Click</button>";
//Add that string to temp container (his html will be replaced, not added).
tempContainer.innerHTML = strElem.trim();//Trim function used to prevent empty textnodes before element.
//Get element from temp container.
var button = tempContainer.children[0];
//Empty tempContainer for better security (But about which security I'm talking in JavaScript in string element generation :) )
tempContainer.innerHTML = '';
//Add your button to container.
container.appendChild(button);
//Add event listener to button:
//document.getElementById("btn_" + i).onclick = clicky;
//Better way to add event listener:
button.addEventListener('click', clicky);
}
DEMO: http://jsfiddle.net/3cD4G/1/

Change the onClick function to target the edit buttons

I have the following script
var counter = 0;
function appendText(){
var text = document.getElementById('usertext').value;
if ( document.getElementById('usertext').value ){
var div = document.createElement('div');
div.className = 'divex';
var li = document.createElement('li');
li.setAttribute('id', 'list');
div.appendChild(li);
var texty = document.createTextNode(text);
var bigdiv = document.getElementById('addedText');
var editbutton = document.createElement('BUTTON');
editbutton.setAttribute('id', 'button_click');
var buttontext = document.createTextNode('Edit');
editbutton.appendChild(buttontext);
bigdiv.appendChild(li).appendChild(texty);
bigdiv.appendChild(li).appendChild(editbutton);
document.getElementById('button_click').setAttribute('onClick', makeAreaEditable());
document.getElementById('usertext').value = "";
counter++;
}
};
var makeAreaEditable = function(){
alert('Hello world!');
};
I want the makeAreaeditable function to work when the Edit button is pressed(for each of the edit buttons that are appended under the textarea).. In this state, the script, alerts me when i hit the Addtext button.
the following is the html. P.S. i need this in pure javascript, if you can help. thanks
<textarea id="usertext"></textarea>
<button onClick="appendText()">Add text </button>
<div id="addedText" style="float:left">
</div>
instead of:
document.getElementById('button_click').setAttribute('onClick', makeAreaEditable());
you need to do this:
editbutton.onclick = makeAreaEditable;
the function's name goes without brackets unless you want to execute it
instead of obtaining the element from the DOM using document.getElementById('button_click')
you can use the editbutton variable already created. this object is the DOM element you are looking for
SIDE NOTE:
the standard way to do it is to add the onclick property before appending the element

Categories