How do I append an existing html element to another element? - javascript

I want to append multiple copies of div with id hello into the div with id container. How do I do this using javascript?
<div id="container">
</div>
<div id="hello">
<p>Hello</p>
</div>

Using cloneNode and appendChild.
Since ids should be unique in a document, I switched things to use a class hello instead.
function makeCopy() {
const target = document.getElementById("container");
const source = document.querySelector(".hello");
const clone = source.cloneNode(true);
target.appendChild(clone);
}
.hello {
padding: 3px;
margin: 3px;
border: 1px dotted orange;
}
<div id="container">
This is the container.
</div>
<button onclick="makeCopy()">Add a clone of hello above</button>
<div class="hello">
<p>Hello</p>
</div>

https://www.w3schools.com/jsref/met_node_appendchild.asp
check this out, it will solve your problem, BUT use a class for the tag not an ID. IDs are unique, a class is for multiple elements.
you can call class in CSS like this
.className {
/*CODE*/
}

you can use append() method:
$(document).on('click', function(){
$('#container').append( $('#hello') );
});

Related

How to get element html() and edit or remove some classes/elemetns

Im trying to get the html of container and remove some useless element and classes before send to Database but i dont know why this is not working
$('button').click(function(){
var html = $('.wrapper-container').html();
$(html).find('.single-col').removeClass('.single-col')
$(html).find('p').remove();
console.log(html);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div class="wrapper-container">
<div class="single-col">Hello</div>
<div class="single-col">World</div>
<p>Junk text</p>
</div>
<button type="button">Clear html</button>
$('button').click(function(){
var container = $('.wrapper-container').clone(); // operate on a clone to not modify the real thing
container.find('.single-col').removeClass('single-col'); // not .single-col in removeClass
container.find('p').remove();
console.log(container.html());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div class="wrapper-container">
<div class="single-col">Hello</div>
<div class="single-col">World</div>
<p>Junk text</p>
</div>
<button type="button">Clear html</button>
I'd suggest the following approach, instead of trying to modify a string use a cloned element, or document fragment:
$('button').click(function() {
// using 'let' instead of 'var' to scope the variable to
// local block; and using the .clone() method, with
// the (Boolean) true argument to include the descendant
// elements (but without cloning event-handlers):
let clone = $('.wrapper-container').clone(true);
// here we find the '.single-col' elements in the
// cloned node, and remove that class (this doesn't
// remove the class attribute, just the class-name):
clone.find('.single-col').removeClass('single-col');
// here we find the <p> element(s), and remove them:
clone.find('p').remove();
// here we append the cloned element, using the append()
// method, to the #resultingDOM element:
$('#resultingDOM').append(clone);
// here we update the text of the #resultingHTML
// element, using the text() method, to the innerHTML
// of the cloned .wrapper-container elememt:
$('#resultingHTML').text(
clone.html()
);
console.log(clone);
})
*,
::before,
::after {
box-sizing: border-box;
font-size: 1rem;
line-height: 1.5;
margin: 0;
padding: 0;
}
.wrapper-container {
margin: 1em auto;
width: 80vw;
}
.single-col {
--color: #f90;
}
.wrapper-container :not(div) {
--color: lime;
}
.wrapper-container>* {
background-image: linear-gradient(90deg, var(--color, aqua), #fffa);
}
.wrapper-container::before,
.wrapper-container>*[class]:not([class=""])::before {
content: '(.' attr(class) ')';
}
#resultingHTML {
white-space: pre-wrap;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div class="wrapper-container">
<div class="single-col">Hello</div>
<div class="single-col">World</div>
<p>Junk text</p>
</div>
<button type="button">Clear html</button>
<!-- two new elements to show the results, one is the DOM
produced by jQuery manipulation of the clone, the
other is to show the resulting HTML string from that
DOM manipulation: -->
<div id="resultingDOM"></div>
<div id="resultingHTML"></div>
References:
clone().
find().
html().
removeClass().
text().

Is it possible to remove an html element and keep your children with javascript?

I have the following structure .. I would like to remove div.son but keepdiv.grandson, is that possible ?! or changing your <tag> would also be a solution .. ex: changing from <fieldset> to a <div>, remembering that I do not have access to HTML, every change must be done using ** javascript **!
<div class="father">
<fieldset class="son">
<div class="grandson">Content here</div>
<div class="grandson">Content here</div>
<div class="grandson">Content here</div>
<div class="grandson">Content here</div>
</fieldset>
</div>
I tried to use the removeChild () function of ** javascript **, but it removes the entire element.
It's possible with vanilla JavaScript by deep cloning the node of grandson before removing anything else. and then appending it back to the parent. Of course if you want to place it somewhere else, you need to append needed logic of DOM traversing. (CSS section is only for visual validation of the result)
const grandson = document.querySelector('.grandson');
const father = grandson.closest('.father');
const clonedGrandson = grandson.cloneNode(true);
father.querySelector('.son').remove();
father.appendChild(clonedGrandson);
.father {
background-color: red;
padding: 20px;
}
.son {
background-color: blue;
padding: 20px;
}
.grandson {
background-color: green;
padding: 20px;
}
<div class="father">
<fieldset class="son">
<div class="grandson">
<p>Save me</p>
</div>
</fieldset>
</div>
You may take a look at this answer, try to use the search bar next time.
https://stackoverflow.com/a/170056/10944905
In case you just want to jump all over the answer.
var cnt = $(".remove-just-this").contents();
$(".remove-just-this").replaceWith(cnt);

Wrap multiple elements in new div without destroying them - Javascript DOM manipulation

I am trying to 'de-jquery' some code.
I have a div like so:
<div id="main">
<div class="blue"></div>
<div class="green"></div>
<div class="yellow"></div>
</div>
And I wish to insert a wrapper div around all elements except the first. The full number of elements is undetermined, there could be more.
The current solution uses jquery nextAll and wrapAll to produce the following result:
HTML
<div id="main">
<div class="blue"></div>
<div class="wrapper">
<div class="green"></div>
<div class="yellow"></div>
</div>
</div>
jQuery
$(".blue").each(function() {
$(this)
.nextAll()
.wrapAll('<div class="wrapper"></div>');
});
How can I remove all jQuery from this and make it vanilla?
I cannot see any wrap type methods. I could grab the HTML that doesn't have index of [0] and insert it into a new div, then insert that after .blue but that seems messy. Is there a better way?
edit: oh you just want to skip the first item…
skip this solution to the new solution at the bottom.
// this is how you can grab a node.
// alternatively you could use document.querySelectorAll
// (wich will be similar to how $() works)
const blue = document.querySelector('.blue');
// if you desire to use querySelectorAll you can have something similar to
// .each() like: [...document.querySelectorAll('.blue')].map(element => {});
// this is not a necessity but keeps code a little more organized,
// instead of throwing this into line 22.
const nodes = [];
let element = blue;
while(element = element.nextElementSibling) {
nodes.push(element);
}
// let's create a new div
const wrapper = document.createElement('div');
// and add the classname of your desire.
wrapper.classList.add('wrapper');
// now let's iterate over all nodes we stored earlier:
nodes.map(element => wrapper.appendChild(element));
// and append the wrapper to the .main div:
blue.parentNode.appendChild(wrapper);
// and for the fun of it, let's display the outcome:
document.body.appendChild(document.createElement('code')).textContent = blue.parentNode.outerHTML;
div {
padding: 2px;
border: 1px dotted #000;
min-height: 20px;
box-sizing: border-box;
position: relative;
}
<div id="main">
<div class="blue"></div>
<div class="green"></div>
<div class="yellow"></div>
</div>
i just realized you just want to iterate after the first child…
let's try this then:
// let's grab the main element:
const main = document.querySelector('#main');
// you could also do this: document.querySelector('.blue').parentNode;
// now let's grab the children of that node and strip the first one:
const nodes = [...main.children].splice(1);
// now let's create the wrapper div
const wrapper = document.createElement('div');
wrapper.classList.add('wrapper');
// and append all children:
nodes.map(node => wrapper.appendChild(node));
// and ofc add the wrapper to the container:
main.appendChild(wrapper);
div {
padding: 2px;
border: 1px dotted #000;
min-height: 20px;
box-sizing: border-box;
position: relative;
}
<div id="main">
<div class="blue"></div>
<div class="green"></div>
<div class="yellow"></div>
</div>
Try below code.
var allBlues = document.querySelectorAll(".blue");
var divWrapper = document.createElement("div");
divWrapper.className = "wrapper";
for(var i = 0; i < allBlues.length; i++){
// Iterate through all the siblings.
var tempEle;
while(tempEle = allBlues[i].nextElementSibling){
divWrapper.appendChild(tempEle);
}
}
main.appendChild(divWrapper);
.blue{
}
<div id="main">
<div class="blue"></div>
<div class="green"></div>
<div class="yellow"></div>
</div>

how to change the attributes of child divs from the parent div through javascript?

#va{
color:yellow;
}
#v{
color:pink;
}
<div id = "va">
<div id ="v">my name is </div>
<div>khan</div>
</div>
i have tried using document.getelementbyid("va").style.color="yellow"; but the color of element v is not changing i want to change its color by the id of parent i want it to be done through javascript as it is the simple example of the situation in which i am traped plz help
$("#va>#v").css("background-color","green")
#va{
color:yellow;
}
#v{
color:pink;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id = "va"> asdasd
<div id ="v">my name is </div>
<div>khan</div>
</div>
Use > the direct child selector.
The selector will select the direct child(with id v) of element with id va and change color to red
With jquery you have two options, using the .children() method or using .find() method, take a look in this snippet:
$("#va").children().css("color", "red");
//$("#va").find("#v").css("color","blue");
#va {
color: yellow;
}
#v {
color: pink;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="va">
<div id="v">
my name is
</div>
<div>
khan
</div>
</div>
If you want to change the color of ID v, use getElementById("v") rather that getElementById("va")
document.getElementById("v").style.color = "yellow";
#va {
color: yellow;
}
#v {
color: pink;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="va">
<div id="v">my name is </div>
<div>khan</div>
</div>
you can change the class attribute of any element and create the css to what you need using:
document.getElementById("va").setAttribute("class", "yellow-class");
css would bw something like:
.yellow-class{
color: yellow;
}
Colors styles only affect child nodes if the child node's color property is set to initial.
#va{
color:yellow;
}
#v{
color:initial;
}
However, this will remove the default pink color from your tag. There are lots of different ways you could solve this problem but the simplest would be to just create a new style rule and simply use js to add a class to #va to change the style.
#va.yellow #v {
color: yellow;
}
And use this js.
document.getElementById("va").className += " yellow";

Add a unique class to each div inside of a wrapping div

I am using twig and JavaScript to create a slideshow, but I need to add a unique css class to each div inside of a wrapping div. The divs inside are all dynamically created and I can't edit the html. I was hoping to either do this with twig or JavaScript.
Any help is much appreciated.
For example:
<div class="slider-wrapper">
<div>image</div> (These are the divs I need to add a unique css class to)
<div>image</div>
<div>image</div>
</div>
Here's a JavaScript solution (I know nothing of Twig). This should be fairly self-explanatory:
// select divs that are children of the wrapper
var divs = document.querySelectorAll(".slider-wrapper > div");
// loop over them
for (var i = 0; i < divs.length; i++) {
// add the unique class using whatever class-naming system you prefer
divs[i].classList.add("c" + (i+1));
}
.c1 { background-color: red; }
.c2 { background-color: green; }
.c3 { background-color: blue; }
<div class="slider-wrapper">
<div>image</div>
<div>image</div>
<div>image</div>
</div>
I've added the c1-3 classes with colours just so that there is something to look at if you click "Run code snippet", but obviously you'd do your own classes.
Note: you had a typo in your html, you need an equals sign after class.
I'm using jquery.
Suppose, you've a html like this:
<div class="parent">
<div class="child"></div>
<div class="child"></div>
</div>
You can add classes to your children like this:
let children = $('.parent').children().addClass("hello");
Example: Jsfiddle
(You can do an inspect element to check that hello has been added to the child classes)

Categories