Removing and creating HTML elements with same id using Javascript - javascript

I have a button that, when pressed, executes something like
function click(){
element = document.getElementById("element");
element.parentNode.removeChild(element);
var newelement = document.createElement("div");
body.appendChild(newelement);
newelement.id = "element";
}
I have also tried using element.outerHTML = "" instead of removeChild with no success. Before adding the bit about deleting the previous element with the id "element" things worked fine on the first click and an div named "element" was appended to the body. (Of course, on the second click, another element named "element" is appended, and I want to keep the id unique to one element.) Now, with the bit about removing previous elements, my button.onClick doesn't even do anything.
Another important piece of context: I'm trying to do this for elements that are generated using user input, so there's no guarantee on how many of these things are made--I just want them deleted when the user wants to generate more of them.
On the first click, I'm attempting to remove an empty element. Does that break something?

body does not exist in the scope you've provided and would throw an exception. I would try:
var body = document.querySelector("body");
See this for a example using your code:
https://jsfiddle.net/k0wL4y7p/2/
Also make sure you use var on all local variables so they are not declared globally. See below to learn about variable scope:
When to use var in Javascript

How about this... don't remove the Parent Element (Div1); instead to remove the children. Then, create the child and append it to the parent element.
Note: you must iterate over it to remove all child nodes & for p element id p1/p2 generate dynamic id or use class if you need it.
Your JS:
$(document).ready(function() {
$("#btn1").click(function() {
var element = document.getElementById("div1");
while (element.firstChild) {
element.removeChild(element.firstChild);
}
var para = document.createElement("p");
var node = document.createTextNode("New element after click.");
para.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(para);
});
});
I prefer JQuery - no loop
$(document).ready(function(){
$("#btn1").click(function(){
$("#div1").empty();
$("#div1").append(" <p>Appended element after click</p>");
});
});
Your Html
<body>
<div id="div1">
<p id="p1">Paragraph element before click.</p>
<p id="p2">Another paragraph beofre click.</p>
</div>
<button id="btn1">Remove </button>
</body>
Hope it helps.

Related

Display outerHTML of multiple elements when the element is created by user

I have a JavaScript program that will create an element each time a button is pressed.
I use:
var element = document.createElement("div");
element.innerHTML = "hi";
document.body.appendChild(element);
I want to make it so when a user creates an element by clicking the button, then it will generate the element's html code or the outerHTML. But I also want it to do this if the user clicked the first button multiple times. So that means that I want it to generate the outer html for every element they make when they push the button. For this, I use:
function CreateElement() {
var element = document.createElement("div");
element.innerHTML = "hi";
document.body.appendChild(element);
var code = element.outerHTML;
}
However, the problem is that there are multiple elements that were created that were under the variable "element". So I want the, "code" variable to contain the outerHTML of all of the elements. I've tried:
function createElement() {
var code = element.outerHTML;
code = code + element.outerHTML //will add the outer html to the variable each time a new element is created
}
...but it always just replaces the whole variable instead of adding the outerhtml to the variable each time the button is clicked to make an element. My goal is to make the variable "code" look something like "<div>hi</div> <div>hi</div>" (as a string)
Thanks for any help
Append each dynamic element into a single container, then take that container's innerHTML:
const container = document.querySelector('.container');
const button = document.querySelector('button');
function createElement() {
var element = document.createElement("div");
element.textContent= "hi";
container.appendChild(element);
console.log(container.innerHTML);
}
button.onclick = createElement;
<button>click</button>
<div class="container"></div>
Also, just a suggestion regarding element.innerHTML = "hi"; - best to only use innerHTML when deliberately setting or retrieving HTML markup. If you just have text, it's faster, safer, and more appropriate to use .textContent.

Inserting div into existing div with class only

I'm trying to create a new div in Javascript with two spans in it, each containing a string of text. They are then meant to be inserted before div.two in div.inner.
The div I'm trying to insert it into only has a class and I cannot target it by any ID, unfortunately.
I have also created a codepen here: https://codepen.io/lisaschumann/pen/BXqJKY
Any help is massively appreciated!
HTML
<html>
<div class="inner">
<div class="one"></div>
<div class="two"></div>
</div>
</html>
JS
window.onload=function(){
var infobox = document.createElement("div");
infobox.classList.add('infobox');
var spanOne = document.createElement("div");
var spanOneText = document.createTextNode('Important text 1');
var spanTwo = document.createElement("div");
var spanTwoText = document.createTextNode('Important text 2');
spanOne.appendChild(spanOneText);
spanTwo.appendChild(spanTwoText);
infobox.appendChild(spanOne);
infobox.appendChild(spanTwo);
var targetDiv = document.getElementsByClassName("inner");
targetDiv.insertBefore(infobox, targetDiv.childNodes[1]);
}
Errors:
Cannot read property '1' of undefined
at window.onload
The main issue is that getElementsByClassName returns a live collection of nodes rather than one node and so you would need to access the correct node in that list similar to an array: targetDiv[0], perhaps.
The easier method is to use querySelector to grab the element you want using its class, for example:
var parent = document.querySelector(".inner");
var two = document.querySelector(".two");
parent.insertBefore(infobox, two);
But! there's even a shortcut method you can use here that allows you to add an HTML string direct to the DOM which might save you a bit of time, and some code.
// Create the HTML
const html = `
<div>
<span>Text alpha</span>
<span>Text beta</span>
</div>`;
// Grab the element containing your "two" class
const two = document.querySelector('.inner .two');
// Using insertAdjacentHTML to add the HTML before the two element
two.insertAdjacentHTML('beforebegin', html);
<div class="inner">Inner
<div class="one">one</div>
<div class="two">two</div>
</div>
insertAdjacentHTML
This doesn't work because of these lines
var targetDiv = document.getElementsByClassName("inner");
targetDiv.insertBefore(infobox, targetDiv.childNodes[1]);
document.getElementsByClassName returns a NodeList. targetDiv.childNodes is undefined, because childNodes doesn't exist on a NodeList.
You need to either use a list operation like Array.prototype.forEach, change getElementsByClassName to getElementByClassName (note the s) or access the first node in the node list using the array indexer syntax.
I assume you meant to do something like this:
var targetDiv = document.getElementByClassName('inner')
targetDiv.insertBefore(infobox, targetDiv.childNodes[1])
This will insert a node in between the first and second child of the first DOM node with the class inner.
Try this out , targetDiv is an array by default due to the getElementsByClassName method , even though it has a single element.Hence you need to specify the index i.e. 0 ( as it's the first element of the array)
var targetDiv = document.getElementsByClassName("inner")[0]; targetDiv.insertBefore(infobox, targetDiv.children[1]); }
Using JQuery
$(document).ready(function(){
$(`<div>Important text 1<span></span>Important text 2<span></span></div>`).insertBefore( ".inner .two" );
)
I would encourage you to use JQuery and then shift to vanilla javascript later on. You can do simple tasks like this in just few lines of code and it is also easily debuggable because of that

Javascript: appendchild append div not working

i want to dynamically add div element to my page.searching around including Stackoverflow gives me this sample code:
var main = document.getElementById('MasterContainer'); //manually defined div with this id
var div = document.createElement('div');
div.setAttribute("id","container1");
main.appendChild(div);
note: its inside a document.ready function.
and the result does not contain container1 div.
The code should be fine, check if the element with id #MasterContaienr is on the page and the name has been write well

get the div parent element of a clicked element, in order to get the p class in the same div

I have a div that looks like this:
<td id="monday">
<p class="outter">whatever here</p>
<p class="hidden" style="display:none">Some content I want to get</p>
</td>
Now the problem is - the td id will change (this is just one of many).
So what I'm trying to do, is when a user clicks on the .outter (it'll always be called outter), I want to find the td id, in order to then get access to the p class (which will always be 'hidden').
So I've tried this (document.body is to get round a dynamic loading problem I had):
$(document.body).on('click', '.outter', function() {
var info = $(this).parent("td").$(".hidden").text();
$("#rightBox").css("width", "200px");
$("#rightBox").css("background", "#f0f0f0");
$("#rightBox").empty();
$("#rightBox").append(info);
});
The issue I am having is in the very first line, getting the variable.
I want to say this particular .outter class, find it's parent, then find the hidden class within it. Then get the text within that hidden class. Then take that variable and dump it into #rightBox;
Can anybody help?
The line var info = $(this).parent("td").$(".hidden").text(); throws an error, you should use find or children method, as the target element is a next direct sibling of the clicked element, you can use next method, you don't need the ID of the parent element.
$(document.body).on('click', '.outter', function() {
// var info = $(this).closest('td').find('.hidden').text();
var info = $(this).next('.hidden').text();
$("#rightBox").css({"width": "200px", "background": "#f0f0f0"})
.html(info);
});
Note that you can also create a class and use addClass method instead of css method, this makes your code a little cleaner.
You can do like this:
$(document.body).on('click', '.outter', function() {
var info = $(this).next().text();
$("#rightBox").css("width", "200px");
$("#rightBox").css("background", "#f0f0f0");
$("#rightBox").empty();
$("#rightBox").append(info);
});
Demo: http://jsfiddle.net/eMzcx/

Insert a div element as parent

I'm just wondering if the following is possible, lets say we have a dom element and we want to wrap this element in a div. So a div is inserted between the element and it's parent. Then the div becomes the element's new parent.
But to complicate things, elsewhere we have already done things like:
var testElement = document.getElementByID('testID')
where testID is a child of the element to be warapped in a div. So after we have done our insertion will testElement still be valid?
BTW: I'm not using jquery.
Any ideas?
Thanks,
AJ
You can use replaceChild [docs]:
// `element` is the element you want to wrap
var parent = element.parentNode;
var wrapper = document.createElement('div');
// set the wrapper as child (instead of the element)
parent.replaceChild(wrapper, element);
// set element as child of wrapper
wrapper.appendChild(element);
As long as you are not using innerHTML (which destroys and creates elements), references to existing DOM elements are not changed.
Assuming you are doing your manipulation using standard DOM methods (and not innerHTML) then — yes.
Moving elements about does not break direct references to them.
(If you were using innerHTML, then you would be destroying the contents of the element you were setting that property on and then creating new content)
You probably want something like:
var oldParent = document.getElementById('foo');
var oldChild = document.getElementById('bar');
var wrapper = document.createElement('div');
oldParent.appendChild(wrapper);
wrapper.appendChild(oldChild);
In pure JS you can try something like this...
var wrapper = document.createElement('div');
var myDiv = document.getElementById('myDiv');
wrapper.appendChild(myDiv.cloneNode(true));
myDiv.parentNode.replaceChild(wrapper, myDiv);
Here is another example, only the new element wraps around 'all' of its child elements.
You can change this as necessary to have it wrap at different ranges. There isn't a lot of commentary on this specific topic, so hopefully it will be of help to everyone!
var newChildNodes = document.body.childNodes;
var newElement = document.createElement('div');
newElement.className = 'green_gradient';
newElement.id = 'content';
for (var i = 0; i < newChildNodes.length;i++) {
newElement.appendChild(newChildNodes.item(i));
newChildNodes.item(0).parentNode.insertBefore(newElement, newChildNodes.item(i));
}
You will want to modify the 'document.body' part of the newChildNodes variable to be whatever the parent of your new element will be. In this example, I chose to insert a wrapper div. You will also want to update the element type, and the id and className values.

Categories

Resources