How copying elements without deleting originals? - javascript

I have a loop to duplicate an array, and another to add copy in another div.
Both loop work good but original element are deleted, someone can explain me why?
And how can i fixe it? Thank you!
var mesElements = document.querySelectorAll('.element');
var catchCopy = document.querySelector('.parent_copy');
var mesElementsCopie = []
for(var j = 0; j < mesElements.length; ++j){
mesElementsCopie[j] = mesElements[j];
}
for(var k = 0; k < mesElements.length; ++k){
catchCopy.appendChild(mesElementsCopie[k]);
}
<div class="parent_element" style="background-color: red;">
<div class="element">text</div>
<div class="element">text</div>
<div class="element">text</div>
</div>
<div class="parent_copy" style="background-color: green;"></div>

On this line, you do not copy the node, but rather you create two references to the same DOM node:
mesElementsCopie[j] = mesElements[j];
You should use the cloneNode() method:
mesElementsCopie[j] = mesElements[j].cloneNode(true);

Here's the fixed code:
var mesElements = document.querySelectorAll('.element');
var catchCopy = document.querySelector('.parent_copy');
var mesElementsCopie = []
for(var j = 0; j < mesElements.length; ++j){
mesElementsCopie[j] = mesElements[j].cloneNode(true);
}
for(var k = 0; k < mesElements.length; ++k){
catchCopy.appendChild(mesElementsCopie[k]);
}
<div class="parent_element" style="background-color: red;">
<div class="element">text</div>
<div class="element">text</div>
<div class="element">text</div>
</div>
<div class="parent_copy" style="background-color: green;"></div>
You were adding the same elements you had grabbed from the parent element, so it was just moving them to the parent copy. Use .cloneNode(true) to make sure you're not using the same element.

Related

Selecting every 2nd div inside other div

<div id="random numbers">
<div class="column-1"></div>
<div class="column-1">this value I want to change</div>
<div class="column-1"></div>
</div>
from earlier advice, I have this code:
var elements = document.querySelectorAll('.column-1 a');
for (var i = 0; i < elements.length; i++) {
elements[i].outerHTML = "OVERRIDDEN";
}
the issue I'm having is that this replaces each <a inside each div <div id="random numbers">), while I would like it only to replace the second column-1 inside each random numbers div.
thank you in advance!
document.querySelectorAll('.column-1 a')[1].outerHTML = "OVERRIDDEN";
Just work with i
var elements = document.querySelectorAll('.column-1');
for (var i = 0; i < elements.length; i++) {
if(i%2) { // override 2nd, 4th, etc.
elements[i].outerHTML = "OVERRIDDEN";
}
}
https://jsfiddle.net/ishukshin/av6t6kxz/

.getAttribute() method on elements returned by querySelectorAll()

I'm trying to get the value of data attributes from multiple div elements. The elements are captured into a variable using
querySelectorAll()
I'm getting an error when I loop through the variable that contains the element and use the getAttribute() Method:
<div id="container">
<div class="box" data-speed="2" id="one"></div>
<div class="box" data-speed="3" id="two"></div>
<div class="box" data-speed="4" id="three"></div>
<div class="box" data-speed="5" id="four"></div>
<div class="box" data-speed="6" id="five"></div>
</div>
js:
(function() {
var boxes = document.getElementsByClassName("box");
for (var i = 0; i < boxes.length; i++) {
var r = Math.floor((Math.random() * 254) + 1);
boxes[i].style.background = "rgba(" + r + "," + i*30 + "," + i*45 + ", 1)";
}
})();
var divArray = [];
var divs = document.querySelectorAll(".box");
for (i = 0; i <= divs.length; i++) {
console.log(divs[i]);
var speed = parseInt(divs[i].getAttribute("data-speed"));
};
Jsfiddle https://jsfiddle.net/kshatriiya/L8xsvzL1/1/
When I
console.log(divs[i])
it shows the element, I don't know why I'm unable to use the attribute method on it.
Any pointer would be really appreciated!
Arrays in javascript are 0 index based
use
for (i = 0; i < divs.length; i++) {
instead of
for (i = 0; i <= divs.length; i++) {
due to this you are getting last divs[i] as undefined and thats why console display that error
updated fiddle : https://jsfiddle.net/n3qhan4e/
It's simple
document.querySelectorAll('.box').forEach(elem => console.log(elem.getAttribute('data-speed')));

Select Nodes & Sum values

Question
How do you select text node values identified with a specific attribute (background color #00FF00)?
As I'm new to javascript, I'm not sure how to do the first step:
use the js dom to select the node with 00FF00
split the string with " " as the separator
loop through and add each split[2] with +=
write the sum (240+80+600) to html
Code
<!DOCTYPE html>
<html>
<head>
<script>
window.onload = function() {
var data = document.getElementsByTagName('span');
document.write(data);
};
</script>
</head>
<body>
<div class="box">
<span class="highlight">Dave collected 700 items.</span>
</div>
<div class="box">
<span class="highlight" style="background-color:#00FF00;">Bob collected 240 items.</span>
</div>
<div class="box">
<span class="highlight" style="background-color:#00FF00;">Bob collected 80 items.</span>
</div>
<div class="box">
<span class="highlight" style="background-color:#00FF00;">Bob collected 600 items.</span>
</div>
</body>
</html>
var els = document.querySelectorAll('span.highlight');
var len = els.length;
//console.log(len); //returns 4
var total = 0;
for (var i=0; i < len; i++) {
if (els[i].style.backgroundColor.toLowerCase() === 'rgb(0, 255, 0)') {
var txt = els[i].innerHTML;
//split txt into array
split = txt.split(" ");
total += parseInt(split[2]);
}
}
console.log(total);
Unless you are trying to scrape the content of another site and have no control over the HTML structure, I would recommend adding an additionnal class or an attribute to these that would ease the selection of these nodes.
However, you could do it like:
var els = document.querySelectorAll('span.highlight'),
i = 0,
len = els.length;
for (; i < len; i++) {
if (els[i].style.backgroundColor.toLowerCase() === '#00ff00') {
//code
}
}
As previously mentioned, it's probably best to use a class definition. But if you must select by color, the following code should do it for you.
var data = document.getElementsByTagName('span');
var len = data.length;
for(var i = 0; i < len; ++i){
var styles = data[i].getAttribute('style');
if(styles.indexOf('background-color:#00FF00') != -1){
//Do something
}
}

Instantiate new element class using javascript

How can I instantiate an existing div element using javascript? Lets say I have:
<div class="container">
<div class="myclass">TROLL FACE</div>
</div>
I want to create as many 'myclass' element inside the 'container' class as I want using javascript. How can I do this?
Please help, thanks.
You may want the .clone method.
var ele = $('.myclass');
for (var i = 0; i < 5; i++) {
ele.clone().appendTo('.container');
}
The live demo.
var container = $('.container');
for (var i = 0; i < 5; i++) {
container.append('<div class="myclass">TROLL FACE</div>');
}
You could use the .append() method.
With or without JQuery:
for (var i = 0; i < howMany; ++i) {
// pure js
var div = document.createElement('div')
div.classList.add('myclass')
somePlace.appendChild(div)
// jquery
$("<div></div>").addClass('myclass').appendTo(somePlace)
}
Try this
<div class="container">
<div class="myclass">TROLL FACE</div>
</div>
var $container = $('.container');
var $myclass = $('.container').html();
var mycount ; // Your count
for(var i =0;i< mycount ; i++){
$container.append($myclass)
}

Adding nodes using javascript arrays

I have two arrays var nodes = new Array("alpha","beta","omega");
var childnodes = new Array("one","two","three");. What I want is to create three div elements from nodes array and then add three more div elements to each of the nodes' array div tags so it will look like this.
<div class="alpha">
<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
</div>
<div class="beta">
<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
</div>
<div class="omega">
<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
</div>
How can I achieve this in jquery? My current code does add parent nodes but it does not add child nodes to the parent. How can I make the following code work?
Here is my code
var nodes = new Array("alpha","beta","omega");
var childnodes = new Array("one","two","three");
for (var i = 0; i < nodes.length; i++) {
var parentNodes = "<div class='" + nodes[i] + "'></div>";
console.log(parentNodes);
for (var j = 0; j < childnodes.length; j++) {
var childNodes = "<div class='" + childnodes[j] + "'></div>";
var p = $(parentNodes).attr('class');
console.log($('.' + p).append(childNodes));
$('.' + p).append(childNodes);
console.log(childNodes);
}
$('body').append(parentNodes);
}
Here is jsfiddle code
var nodes = ["alpha","beta","omega"];
var childnodes = ["one","two","three"];
$.each(nodes, function(i, node) {
var div = $('<div>').addClass(node);
$.each(childnodes, function(i, node) {
$('<div>').addClass(node).appendTo(div);
});
div.appendTo('body');
})​
Here is the demo.
Late but another possible example:
var nodes = new Array("alpha","beta","omega");
var childnodes = new Array("one","two","three");
for (var i in nodes) {
var $nodes = $('<div>'+nodes[i]+'</div>');
for(var k in childnodes){
var $child = $('<div>'+childnodes[k]+'</div>');
$child.appendTo($nodes);
}
$nodes.appendTo('#container');
}

Categories

Resources