Deleting specific div's with JavaScript - javascript

I am trying to spawn different div's and remove them after they do their job. A simple version of my code is:
function eraseDiv(){
var c = document.getElementById("cn1");
c.parentNode.removeChild(child);
}
function spawnDiv(){
var x = document.getElementById("test");
var d = document.createElement("div");
d.id = "child";
d.style.width = "500px";
d.style.height = "30px";
var content = "Some text for testing!" + "<a href=\"?\" onclick=eraseDiv(); return false; > Delete</a>";
d.innerHTML = content;
if (document.getElementById("cn1").innerHTML.trim() == "")
document.getElementById("cn1").appendChild(d);
else
document.getElementById("cn2").appendChild(d);
}
<input type="submit" name="Submit" value="Spawn" onclick="spawnDiv(); return false;" />
<div id= "test">
<div id= "cn1"></div>
<div id= "cn2"></div>
</div>'
The problem is that when the first spawned div is deleted, all div's are deleted. Any help is appreciated on how to fix this.

How about something like this:
function eraseDiv(target){
var div = target.parentNode;
var container = div.parentNode;
container.removeChild(div);
}
function spawnDiv(){
var x = document.getElementById("test");
var d = document.createElement("div");
d.style.width = "500px";
d.style.height = "30px";
var content = "Some text for testing!" + "<button onclick=eraseDiv(this);> Delete</button>";
d.innerHTML = content;
if (document.getElementById("cn1").innerHTML.trim() == "")
document.getElementById("cn1").appendChild(d);
else
document.getElementById("cn2").appendChild(d);
}
<button type="button" name="submit" onclick="spawnDiv();">Spawn</button>
<div id= "test">
<div id= "cn1"></div>
<div id= "cn2"></div>
</div>
First thing, since you're returning false every time you obviously don't want to use the submit functionality of your submit input, so change it to a button instead.
Second thing, remove the ID from the spawned div since you should never have two divs with the same ID.
Third thing (like the first thing) since you're not using the link functionality of the anchor element, you should change it to a button instead (using CSS you can style this like an anchor if you want to).
Fourth thing, inside the delete button, add this as a parameter to the eraseDiv function. You can now access the button that was clicked using the function parameter rather than trying to find it by an ID.

The simplest fix to your code without modifying the functionality (and view of the page) of what you did is to replace the href="?" with href="#".
In your original code, when you do something like link with the "?" as the hyperlink, this actually performs a GET request which will reload the page. This is tricky because it makes it seem like your delete code is removing all the spawned divs from both cn1 and cn2 divs.
Changing the href=? to href=# prevents a GET request from happening. Below is a snippet that directly makes this change that results in the correct behavior of your original code (by deleting the spawned element in cn1). You will have to further modify your code to make it do what you want.
function eraseDiv(){
var c = document.getElementById("cn1");
c.parentNode.removeChild(c);
}
function spawnDiv(){
var x = document.getElementById("test");
var d = document.createElement("div");
d.id = "child";
d.style.width = "500px";
d.style.height = "30px";
var content = "Some text for testing!" + "<a href=\"#\" onclick=eraseDiv(); return false; > Delete</a>";
d.innerHTML = content;
if (document.getElementById("cn1").innerHTML.trim() == "")
document.getElementById("cn1").appendChild(d);
else
document.getElementById("cn2").appendChild(d);
}
<input type="submit" name="Submit" value="Spawn" onclick="spawnDiv(); return false;" />
<div id= "test">
<div id= "cn1"></div>
<div id= "cn2"></div>
</div>

Another way of doing it would be to create a id for div like this
<html>
<body>
<input type="submit" name="Submit" value="Spawn" onclick="spawnDiv(); return false;" />
<div id= "test">
<div id= "cn1"></div>
<div id= "cn2"></div>
</div>
<script>
function eraseDiv(j){
var c = document.getElementById('child'+j);
c.parentNode.removeChild(c);
}
var i=1;
function spawnDiv(){
var x = document.getElementById("test");
var d = document.createElement("div");
d.id = "child"+i;
d.style.width = "500px";
d.style.height = "30px";
var content = "Some text for testing!" + "<u ><a onclick=eraseDiv("+i+++"); > Delete</a></u>";
d.innerHTML = content;
if (document.getElementById("cn1").innerHTML.trim() == "")
document.getElementById("cn1").appendChild(d);
else
document.getElementById("cn2").appendChild(d);
}
</script>
</body>
</html>

Related

appending User entered text using createTextNode method

Right now I am trying to figure out how to append CREATED text to a CREATED p element depending on what a user enters into an input text field.
If I set the text after the createTextElement method, it displays just fine when I click the button. BUT what I want is: the user enters text in the input field and then upon clicking the button, the text get's added to the end of the div tag with the id of "mydiv". Any help is appreciated.
HTML:
<body>
<div id="mydiv">
<p>Hi There</p>
<p>How are you?</p>
<p>
<input type="text" id="myresponse">
<br>
<input type="button" id="showresponse" value="Show Response">
</p>
<hr>
</div>
</body>
JAVASCRIPT:
var $ = function(id) {
return document.getElementById(id)
}
var feelings = function()
{
$("myresponse").focus();
var mypara = document.createElement("p");
var myparent = $("mydiv");
myparent.appendChild(mypara);
var myText = document.createTextNode($("myresponse").value);
mypara.setAttribute("id", "displayedresponse");
mypara.appendChild(myText);
$("displayedresponse").appendChild(myText);
}
window.onload = function() {
$("showresponse").onclick = feelings;
}
You need to apply an argument to createTextNode function
You need to read the value of the input field so you can see the text.
Since you will reference mydiv on every click, i think moving mydiv variable to parent scope will suit you better
var $ = function (id) {
return document.getElementById(id)
}
let mydiv = $('mydiv');
$("showresponse").addEventListener('click', feelings);
function feelings() {
let textInput = $('myresponse').value;
var mypara = document.createElement("p");
var myText = document.createTextNode(textInput);
mypara.setAttribute("id", "displayedresponse");
mypara.appendChild(myText);
mydiv.appendChild(mypara);
$("displayedresponse").appendChild(myText);
}

Transferring iframe value to textarea

I'm making an app that submits posts, but I originally designed it with a textarea in mind, I've since put in an iframe to create a rich text field, set the display style to hidden for the textarea and wanted to know how I could modify it to use the iframe value.
HTML
<div id="textWrap">
<div class="border">
<h1>Start Writing</h1><br />
<input id="title" placeholder="Title (Optional)">
<div id="editBtns">
<button onClick="iBold()">B</button>
<button onClick="iUnderline()">U</button>
<button onClick="iItalic()">I</button>
<button onClick="iHorizontalRule()">HR</button>
<button onClick="iLink()">Link</button>
<button onClick="iUnLink()">Unlink</button>
<button onClick="iImage()">Image</button>
</div>
<textarea id="entry" name="entry" rows="4" cols="50" type="text" maxlength="500" placeholder="Add stuff..."></textarea>
<iframe name="richTextField" id="richTextField"></iframe><br />
<button id="add">Submit</button>
<button id="removeAll" onclick="checkRemoval()">Delete All Entries</button>
<ul id="list"></ul>
<ul id="titleHead"></ul>
</div><!--end of border div-->
</div><!--end of textWrap-->
Here is the JS to submit the posts.
//target all necessary HTML elements
var ul = document.getElementById('list'),
removeAll = document.getElementById('removeAll'),
add = document.getElementById('add');
//richText = document.getElementById('richTextField').value;
//make something happen when clicking on 'submit'
add.onclick = function(){
addLi(ul)
};
//function for adding items
function addLi(targetUl){
var inputText = document.getElementById('entry').value, //grab input text (the new entry)
header = document.getElementById('title').value, //grab title text
li = document.createElement('li'), //create new entry/li inside ul
content = document.createElement('div'),
title = document.createElement('div'),
//textNode = document.createTextNode(inputText + ''), //create new text node and give it the 'entry' text
removeButton = document.createElement('button'); //create button to remove entries
content.setAttribute('class','content')
title.setAttribute('class','title')
content.innerHTML = inputText;
title.innerHTML = header;
if (inputText.split(' ').join(' ').length === 0) {
//check for empty inputs
alert ('No input');
return false;
}
removeButton.className = 'removeMe'; //add class to button for CSS
removeButton.innerHTML = 'Delete'; //add text to the remove button
removeButton.setAttribute('onclick', 'removeMe(this);'); //creates onclick event that triggers when entry is clicked
li.appendChild(title); //add title textnode to created li
li.appendChild(content); //add content textnode to created li
li.appendChild(removeButton); //add Remove button to created li
targetUl.appendChild(li); //add constructed li to the ul
}
//function to remove entries
function removeMe(item){
var deleteConfirm = confirm('Are you sure you want to delete this entry?');
if (deleteConfirm){var parent = item.parentElement;
parent.parentElement.removeChild(parent)}
};
function checkRemoval(){
var entryConfirm = confirm('Are you sure you want to delete all entries?');
if (entryConfirm){
ul.innerHTML = '';
}
};
demo I'm working on for reference.. http://codepen.io/Zancrash/pen/VemMxz
you can use either local storage for passing iframe values to the parent DOM.
or ( use this to pass value from iframe to parent container )
var iFrameValue = $('#iframe').get(0).contentWindow.myLocalFunction();
var iFrameValue = $('#iframe').get(0).contentWindow.myLocalVariable;
From IFrame html
<script type="text/javascript">
var myLocalVariable = "text";
function myLocalFunction () {
return "text";
}
</script>

JavaScript cannot insert images into HTML

I'm making a prototype for a program that lets you insert an image URL and you can add to it with animated GIFs (Canvas is not used because animated GIFs cannot be shown). However, when I try to do this, it doesn't work.
<center>
<input type="text" id="tb" placeholder="Image URL" />
<button onClick="ipt()">Import</button>
<button onClick="edit()">Add Effects</button>
<div id="lyr">
</div>
</center>
<script>
function ipt() {
var c = document.getElementById('tb').value;
alert(c);
document.getElementById('lyr').style.background = "url(" + c + ")";
}
</script>
Here's a simple vanilla script that'll do what you want.
It first creates variables for each of the items you want to handle, then creates a click handler for the button.
Feel free to swap out the class selectors for IDs.
https://jsfiddle.net/chxd6bnb/2/
var holder = document.getElementsByClassName('holder');
var image = document.getElementsByClassName('image');
var button = document.getElementsByClassName('showIt');
console.log(button);
button[0].addEventListener('click', function(e) {
e.preventDefault();
var img = image[0].value;
holder[0].style.backgroundImage = 'url(' + img + ')';
});

Javascript:DIV AppendChild

In the below code "objTo" is a div to which i need to insert multiple number of div.
when i use the code for the first time its working.but on the next time its overwriting the existing code.
<script>
var divtest= document.createElement("div");
divtest.innerHTML = "<div>new div</div>"
objTo.appendChild(divtest)
</script>
Where am i going wrong?
I have made a very simple working version for you :
http://jsfiddle.net/hQKy9/
Multiple clicks works the whole time :
Script
function addDiv() {
var objTo = document.getElementById('container');
var divtest = document.createElement("div");
divtest.innerHTML = "new div";
objTo.appendChild(divtest);
}
Html
<div id="container"></div>
<input type="button" onclick="addDiv();" value="Click here to add div"/>
Even through Marc gave the ans before
I found it we can do more like adding ID/Class and CSS like the following way I did
const newChild = document.createElement('div');
newChild.id = 'newly_content';
newChild.innerHTML = `
<p style="font-size: 30px;padding: 200px 0px 10px 0px;">
A new content has been created!
</p>
`;
document.getElementById('ItemID').appendChild(newChild);

Javascript help, writing html elements

How do I write this HTML using javascript.
<div id="resizeControl">
<input type="image" src="resuce.png" />
<input type="image" src="enlarge.png" />
</div>
and append it to a slidegallery object..
.net
var image1= document.createElement("input"); //create your input
image1.setAttribute('src','resuce.png'); //set the attributes
image1.setAttribute('type','image');
var image2= document.createElement("input");
image2.setAttribute('src','enlarge.png');
image2.setAttribute('type','image');
var resizeControl = document.createElement("div"); //create the parent div
resizeControl.id = "resizeControl"; //assign the id
resizeControl.appendChild(image1); //append your images to the new div
resizeControl.appendChild(image2);
document.body.appendChild(resizeControl); //append the div to your body (or other element)
Code example on jsfiddle
More information on concepts used:
Node.appendChild()
document.createElement()
element.setAttribute()
var div = document.createElement('div'),
input1 = document.createElement('input'),
input2 = document.createElement('input');
div.id = 'resizeControl';
input1.type = 'image';
input1.src = 'resuce.png';
input2.type = 'image';
input2.src = 'enlarge.png';
div.appendChild(input1);
div.appendChild(input2);
document.body.appendChild(div);
Javascript:
document.getElementById("Main").innerHTML += "<strong>Hello!</strong>";
document.getElementById("Main").innerHTML += "<div style='background:red'>Rrrrred!</div>";
HTML:
<div id="Main">
Why...
</div>

Categories

Resources