Duplicate Div - Remove option prevents additional Div Duplication - javascript

I'm new to using javascript and have come up against a bit of a wall where I was looking for code to duplicate a DIV. I found the following code:
<html>
<body>
<form name="myform">
<input type="button" value="Click here" onclick="duplicate()">
<div id="original">
duplicate EVERYTHING INSIDE THIS DIV
</div>
<div id="duplicater">
duplicate EVERYTHING INSIDE THIS DIV
<input type="button" value="Remove Div" onclick="this.parentNode.style.display = 'none'">
</div>
<script>
var i = 0;
var original = document.getElementById('duplicater');
function duplicate() {
var clone = original.cloneNode(true); // "deep" clone
clone.id = "duplicater" + ++i;
// or clone.id = ""; if the divs don't need an ID
original.parentNode.appendChild(clone);
}
</script>
</body>
</html>
This works quite well. I added a Remove Div button so if the user decided they added one Div too many they would have the option to remove it. However, in testing I found if the user Remove Div all the way back to the first Div, any further Duplicate Div does not display. So the user would have to restart the page. To resolve this I tried to include an IF...ELSE.
<html>
<body>
<form name="myform">
<input type="button" value="Click here" onclick="duplicate()">
<div id="original">
duplicate EVERYTHING INSIDE THIS DIV
</div>
<div id="duplicater">
duplicate EVERYTHING INSIDE THIS DIV
<input type="button" value="Remove Div" onclick="this.parentNode.style.display = 'none'">
</div>
<script>
var i = 0;
var original = document.getElementById('duplicater');
function duplicate() {
if (document.getElementById("duplicater")=="none")
{
document.getElementById("duplicater")="";
}
else
{
var clone = original.cloneNode(true); // "deep" clone
clone.id = "duplicater" + ++i;
// or clone.id = ""; if the divs don't need an ID
original.parentNode.appendChild(clone);
}
}
</script>
</body>
</html>
However, this does not work. I fully admit to being no coding guru and wouldn't be surprised if it is a simply syntax issue, but any points with this would be greatfully accepted.

Your problem is here:
this.parentNode.style.display = 'none'
This is setting the parent node (the form) to not display (which isn't the same as removing it). What you want to do is find the lastChild to the of the parent node and remove it.

Matt has your answer, I got distracted so here's a late response. In your code:
> <input type="button" value="Remove Div" onclick="this.parentNode.style.display = 'none'">
does not "remove" the node, it just hides it. To remove the node:
<input type="button" value="Remove Div" onclick="this.parentNode.parentNode.removeChild(this.parentNode)">
Also:
> if (document.getElementById("duplicater")=="none")
getElementById returns either a DOM node with a matching ID, or null if there isn't one. Neither will ever be equivalent to the string "none", therefore the above will always return false. Which is a good thing because in the line:
> document.getElementById("duplicater")=""
You will be trying to assign to null or a DOM element, both of which are not permitted. In the case that the left hand side evaluates to null , an error will result. Where it resolves to a DOM element, anything can happen (since host objects can do what they like) but likely an error will result.

Related

Beginner/ I try to use Onclick to unhide element but it doesn't work

I want to make a page to upload the avatar.
By default, I use the vector to show where the image will appear
and then provide a button to upload the URL to change the avatar.
That's all it is! But the script still doesn't work.
Pleased to hear your feedback on how to fix it. Bless
<img id="put_image_here_bitch" src="https://cdn0.iconfinder.com/data/icons/finance-vol-2-4/48/77-512.png" alt="" width="100px" height="100px">
<div class="block" > The person who uploads this is cool
</div>
<button onclick="hideElement()">Click to upload photo by URL</button>
<div>
<input id="input" autofocus class='hidden_element' style="display: none;" type="text" id="input">
</div>
<div>
<button class='hidden_element' style="display: none;" onclick="uploadImage()">UPLOAD</button>
</div>
This is my script
function hideElement(){
var hide = document.getElementsByClassName('hidden_element');
if (hide.style.display === "none") {
hide.style.display = "block";
} else {
hide.style.display = "none";
}
}
var uploadImage = function(){
image = document.getElementById('input').value;
showImage = document.getElementById('put_image_here_bitch').setAttribute('src', image);
};
As stated in the comments, .getElementsByClassName() returns a collection of elements, not a single element and your code attempts to call the style property of the collection, which doesn't exist.
Instead, you need to loop through the collection and operate on the elements within the collection individually, but don't use .getElementsByClassName() and instead use .querySelectorAll().
var hidden = document.querySelectorAll('.hidden_element');
function hideElement(){
// Loop over the colleciton elements
hidden.forEach(function(element){
if (element.style.display === "none") {
element.style.display = "block";
} else {
element.style.display = "none";
}
});
}
var uploadImage = function(){
image = document.getElementById('input').value;
showImage = document.getElementById('put_image_here_bitch').setAttribute('src', image);
};
<img id="put_image_here_bitch" src="https://cdn0.iconfinder.com/data/icons/finance-vol-2-4/48/77-512.png" alt="" width="100px" height="100px">
<div class="block" > The person who uploads this is cool
</div>
<button onclick="hideElement()">Click to upload photo by URL</button>
<div>
<input id="input" autofocus class='hidden_element' style="display: none;" type="text" id="input">
</div>
<div>
<button class='hidden_element' style="display: none;" onclick="uploadImage()">UPLOAD</button>
</div>
But, beyond that, you should also avoid using inline styles as they are the most specific way of setting a style and therefore the hardest to override. They also often require duplicated code to be written. Instead, use CSS classes as shown below:
// Get references to the DOM elements that you'll need to work with
const btnUpload = document.querySelector("button"); // find the first button
const hidden = document.querySelectorAll(".hidden");
const upload = document.querySelector(".upload");
// Do your event binding in JavaScript, not in HTML
btnUpload.addEventListener("click", hideElement);
upload.addEventListener("click", uploadImage);
function hideElement(){
// Loop over the collection of hidden elements
hidden.forEach(function(item){
// See how much more simple it is to work with classes?
item.classList.toggle("hidden");
});
}
function uploadImage(){
showImage = document.getElementById('put_image_here_bitch').setAttribute('src', input.value);
};
.hidden { display:none; }
<img id="put_image_here_bitch" src="https://cdn0.iconfinder.com/data/icons/finance-vol-2-4/48/77-512.png" alt="" width="100px" height="100px">
<div class="block" > The person who uploads this is cool
</div>
<button>Click to upload photo by URL</button>
<div>
<input id="input" autofocus class='hidden' type="text" id="input">
</div>
<div>
<button class='hidden upload'>UPLOAD</button>
</div>
simple.. getElementsByClassName() returns an HTMLCollection with all DOM elements containing that class. An HTMLCollection is like an array ( but not really ) containing element references.
thus you need to define which entry in the array you want to handle ( even if there's only one )
your code should work by simply adding [0] to your DOM read ( the '0' means the first element in the collection )
ex:
var hide = document.getElementsByClassName('hidden_element')[0];

can I remove a line in my HTML code with javascript?

I have this code:
<div class="input">
<input type="number" id="myID" oninput="myFunction()">
<div>
<h3>MY TEXT</h3>
</div>
</div>
and I want to make a javascript code to remove the div below the input field whenever I write anything in the input
..........
I tried this code:
function myFunction(){
var field = document.getElementById("myID");
var num = field.value;
var parent = field.parentNode;
parent.innerHTML = field.outerHTML;
field.value = num;
}
but it have a problem each time I make an input, I have to re-click inside the input to make it active again
check out the code here
You should not use inline HTML event attributes to wire up event handlers. That technique is 25+ years old and will not die the death it deserves because people just keep copying it from other code they've seen.
See the comments for the simple explanation:
// Add the event handler to the input in JavaScript, not in HTML
document.getElementById("myID").addEventListener("input", removeElement);
function removeElement(){
// Remove the sibling element that follows the input
document.querySelector("#myID").nextElementSibling.remove();
// Now that the element has been removed, this function is no
// longer required, so remove the event handler to prevent attempts
// to remove it again when it's no longer there. "this" refers to
// the object that caused this function to be invoked (the input
// element in this case).
this.removeEventListener("input", removeElement);
}
<div class="input">
<input type="number" id="myID">
<div>
<h3>MY TEXT</h3>
</div>
</div>
How to remove an HTML element using JavaScript ?
Given an HTML element and the task is to remove the HTML element from the document using JavaScript.
Approach:
Select the HTML element which need to remove.
Use JavaScript remove() and removeChild() method to remove the
element from the HTML document.
Exemple to remove a div :
div.parentNode.removeChild(div);
Follow this link for more information.
I hope I was able to help you.
<div class="input">
<input type="number" id="myID" >
<div id="id2">
<h3>MY TEXT</h3>
</div>
</div>
<script>
document.getElementById("myID").oninput = function() {myFunction()};
function myFunction() {
document.getElementById("id2").innerHTML="";
}
</script>
Problem with using innerHTML is you are basically using a whiteboard. You erase everything on it and you have to redraw it all. That means you would need to reset the value and focus. It is doable, just not practical.
The better thing to do would be to select the element and remove it with .remove()
var field = document.getElementById("myID");
var num = field.value;
if (num.length) {
field.nextElementSibling.remove()
}
It will work, but you will be better off using a class to hide the element. It also has the benefit that if the user deletes the text in the input, you can reshow the message. I would just hide it with a css class with toggle. I would select the div with nextElementSibling.
function myFunction(){
var field = document.getElementById("myID");
var num = field.value;
field.nextElementSibling.classList.toggle('hidden', num.length)
}
.hidden {
display: none;
}
<div class="input">
<input type="number" id="myID" oninput="myFunction()">
<div>
<h3>MY TEXT</h3>
</div>
</div>

Creating a "Copy button"

Well, as I was searching on the internet for some basic codes to examine - I found this one. A simple code which is supposed to copy the selected text. As i am a complete newbie in JS, I check the meaning of the methods that I didn't understand - and rewrited the code, as i make a few adjustments.
And still the code is not working and If someone can explain - this part ""copyit(this.form.select1)"" - Even though I kind of understand "this" - i am not able to understand what is doind here
function copyit(theField) {
var selectedText = document.getSelection();
if (selectedText.type == 'Text') {
var newRange = selectedText.createRange();
theField.focus();
theField.value = newRange.text;
} else {
alert('select a text in the page and then press this button');
}
}
</script>
<form name="it">
<div align="center">
<input onclick="copyit(this.form.select1)" type="button" value="Press to copy the highlighted text" name="btnCopy">
<p>
<textarea name="select1" rows="4" cols="45"></textarea>
</div>
</form>
This is the original code - and it is not working either
<SCRIPT LANGUAGE="JavaScript">
function copyit(theField) {
var selectedText = document.selection;
if (selectedText.type == 'Text') {
var newRange = selectedText.createRange();
theField.focus();
theField.value = newRange.text;
} else {
alert('select a text in the page and then press this button');
}
}
</script>
And in the body of your web page, add the following where you want the text to appear:
<form name="it">
<div align="center">
<input onclick="copyit(this.form.select1)" type="button" value="Press to copy the highlighted text" name="btnCopy">
<p>
<textarea name="select1" rows="4" cols="45"></textarea>
</div>
</form>
onclick="copyit(this.form.select1)"
executes the copyit() function and passes a variable which is later named theField. The variable that is passed is this.form.select1 which is a textarea with ID select1 which is located in the same form as the input you're clicking hence the this.form.
As to why your code isn't working - you should include here the original code before your adjustments. You probably deleted/changed something you shouldn't have.
I'm not sure what you're asking. Are you asking to, when someone clicks on any button/div, it copies a text you want for his clipboard? If no, ignore my comment, if yes, i'll explain:
First place, where should an user click?
<a class="btn" CopydivFunction(#text)">CLICK ME TO Hello.</a>
Now, add the function with JS.
function copyToClipboard(element) {
var $temp = $("<input>");
$("body").append($temp);
$temp.val($(element).text()).select();
document.execCommand("copy");
$temp.remove();
}
Now, place the text you want somebody to copy (hide it):
<h1 id="text" class="hidden">some text. This part won't be seen because of the hidden class, and this is the text that will be copied to your clipboard.</h1>
Place display:none on css:
#text{
display:none;
}
I think you have to add that, so nobody sees it.
And that should be it, click the <a> and you get the text in the h1#text

HTML - Button is cancelled only after second click

I have a very simple code: I want to cancel a button after it's clicked to display something else. I tried this way
HTML:
<div id="container">
<input type="button" value="New game" onclick="newGame()" />
</div>
js:
function newGame() {
var container = document.getElementById("container");
container.removeChild(container.childNodes[0]);
}
What happens is the button gets cancelled only if I click it two times. Where did I get wrong?
I'm sorry if this is a repost, I tried to check but didn't find a quetion identical to mine
It appears as if your code is going to remove the button once you click on it. Is this correct, or are we not looking at the full markup?
If you remove \n (i.e new line) your code will work
try like this
function newGame() {
var container = document.getElementById("container");
debugger;
container.removeChild(container.childNodes[0]);
}
<div id="container"><input type="button" value="New game" onclick="newGame()" /></div>
The reason why your code is not working is, when you hit enter after div, HTML DOM will automatically creates one dummy text node as it's child. hence your input node became the second child for your container.
Working fiddle
Hope it helps :)
try this:
function newGame() {
var container = document.getElementById("container");
// change 0 to 1
container.removeChild(container.childNodes[1]);
}
container.childNodes[0] is a text Node, in which the text is Newline
I gave id to the button and removed it using id.
In your case it is not removing in first time because container.childNodes[0] in first time is not a button. Try your self using console.log in your function.
function newGame() {
var container = document.getElementById("container");
var d_nested = document.getElementById("button_1");
var throwawayNode = container.removeChild(d_nested);
//container.innerHTML='';
}
<div id="container">
<input id="button_1" type="button" value="New game" onclick="newGame()" />
</div>
Alternatively, you could do this:
<div id="container">
<input type="button" value="New game" onclick="document.getElementById('container').removeChild(this);" />
No separate JS file needed.

Duplicate Inner div inside of the Outer div

I am trying to duplicate some divs. I am able to do this, however, when my div is duplicated it is being duplicated on top of my other content. I would like for it to be duplicated in the same div but it seems to be doing it outside of the div. Below is my code, any suggestions?
I think the problem lies within the last line of the javascript function with the parent node append child but I am not sure.
JS
<script>
document.getElementById('button').onclick = duplicate;
var i = 0;
var original = document.getElementById('duplicator');
function duplicate() {
var clone = original.cloneNode(true);
clone.id = "gamesdiv" + ++i;
original.parentNode.appendChild(clone);
}
</script>
HTML/MARKUP
<div id="gamesdiv">
<div id="duplicator">
<table>
<tr>
<td>type</td>
<td><asp:TextBox ID="gamestype" runat="server" Height="16px" Width="92px"></asp:TextBox></td>
<td>name of game: </td>
<td><asp:TextBox ID="namegame" runat="server" Height="17px" Width="118px"></asp:TextBox></td>
</tr>
</table>
</div>
</div>
<button id="button" onclick="duplicate()">Add new game</button>
The gamesdiv is the div I would like for it to be duplicated in and the 'duplicator' div is the div I am duplicating. If you would like to view my html code please ask
It seems like you have two issues:
The first is the gamesdiv height is set to 85, which limits it.
Next, some of the markup has an invalid close (you have a div that looks like <div/> instead of </div>
I have fixed both of these issues here and tweaked your styles slightly:
http://jsfiddle.net/xDaevax/7LLXZ/
Please check this js fiddle: http://jsfiddle.net/Gb69f/
It is solved your problem or not? If not then please tell me what is the problem?
JavaScript
document.getElementById('button').onclick = duplicate;
var i = 0;
var original = document.getElementById('duplicator');
function duplicate() {
var clone = original.cloneNode(true);
clone.id = "gamesdiv" + ++i;
original.parentNode.parentNode.appendChild(clone);
}

Categories