I can only append 1 card element from the following Javascript - javascript

I can only append 1 card element from the following Javascript. Please Help.
var gb = document.getElementById('game-board');
var cardCount = document.getElementsByClassName('card');
var children = document.createElement('div');
var createCards = function() {
for (var i = 0; i < 5; i++) {
children.className = 'card';
gb.appendChild(children);
};
};
createCards();

you have only 1 "children" item that you keep moving inside the loop. One way to fix it is to clone it each time before appending:
var gb = document.getElementById('game-board');
var cardCount = document.getElementsByClassName('card');
var children = document.createElement('div');
var createCards = function() {
for (var i = 0; i < 5; i++) {
children.className = 'card';
gb.appendChild(children.cloneNode(true));
};
};
createCards();

Your code is attempting to append the same div (stored at the children variable) to gb on every iteration of the loop. Try creating a new element for each iteration instead:
var gb = document.getElementById('game-board');
var createCards = function() {
for (var i = 0; i < 5; i++) {
var children = document.createElement('div');
children.className = 'card';
gb.appendChild(children);
};
};
createCards();
.card{
width: 50px;
height: 50px;
border: 1px solid gray;
}
<div id="game-board" ></div>

Related

Having issues creating a for loop for a list created in JS

I'm trying to for loop the H1 object through a list 10 times. I'm not sure where I went wrong any help would be appreciated.
var headOne = document.createElement("H1");
headOne.textContent = "Hello World";
document.body.appendChild(headOne);
var newOrderedList = document.createElement('OL');
newOrderedList.setAttribute("id", "OLJS");
document.body.appendChild(newOrderedList);
var helloWorld = document.getElementById("OLJS");
for (var i = 0; headOne < 10; i++){
var listItems = document.createElement("li");
listItems.innerHTML = headOne[i];
helloWorld.append(listItems);
}
If you want to loop 10 times then do:
for (let i = 0; i < 10; i++) {
// Do something
}
And in your case if you are trying to access each letter of headOne element and append it to the helloWorld list then you can do the following:
for (let i = 0; i < headOne.textContent.length; i++) {
let listItems = document.createElement('li')
listItems.textContent = headOne.textContent[i]
helloWorld.append(listItems)
}
You might also want to read more about Loops and iteration
var headOne = document.createElement("H1");
headOne.textContent = "Hello World";
document.body.appendChild(headOne);
var newOrderedList = document.createElement('OL');
newOrderedList.setAttribute("id", "OLJS");
document.body.appendChild(newOrderedList);
//var helloWorld = document.getElementById("OLJS");
for (var i = 0; i < 10; i++) {
var listItems = document.createElement("li");
listItems.innerHTML = "order list item " + (i + 1);
newOrderedList.append(listItems);
}

Show class div and hide previous - pure javascript

I was actually using a script which allowed me to Show a div onclick and hide others but now I need to do the same with "class" instead of "id".
My current script:
function layout(divName){
var hiddenVal = document.getElementById("tempDivName");
if(hiddenVal.Value != undefined){
var oldDiv = document.getElementById(hiddenVal.Value);
oldDiv.style.display = 'none';
}
var tempDiv = document.getElementById(divName);
tempDiv.style.display = 'block';
hiddenVal.Value = document.getElementById(divName).getAttribute("class");}
What I tried using getElementsByClassName :
function layoutNEW(divName){
var hiddenVal = document.getElementById("tempDivName");
if(hiddenVal.Value != undefined){
var oldDiv = document.getElementById(hiddenVal.Value);
oldDiv.style.display = 'none';
}
var tempDiv = document.getElementsByClassName(divName);
for ( var i=0, len=tempDiv.length; i<len; ++i ){
tempDiv[i].style.display = 'block';
}
hiddenVal.Value = document.getElementById(divName).getAttribute("id");}
Any ideas ?
EDIT : A working example of my current script with "id" : JSFiddle
EDIT 2: It works great, but when the div (class) is cloned, only one of them is showing the div. Do you have an idea about this ? Where is a JSFiddle demonstrating the situation: JSFiddle
I think this is what you'd need. The idea is that you can use a data property on your <a> tags that will tell your click handler which classname to look for when showing an element. From there, you just hide the others. Here's a working demo:
var toggleControls = document.querySelectorAll("[data-trigger]");
var contentDivs = document.querySelectorAll(".toggle");
for (var i = 0; i < toggleControls.length; i++) {
toggleControls[i].addEventListener("click", function(event) {
var trigger = event.target;
var selector = "." + trigger.getAttribute("data-trigger");
var divToShow = document.querySelector(selector);
for (j = 0; j < contentDivs.length; j++) {
contentDivs[j].style.display = "none";
}
divToShow.style.display = "block";
});
}
.toggle {
height: 100px;
width: 100px;
display: none;
}
.div1 {
background-color: red;
}
.div2 {
background-color: blue;
}
.div3 {
background-color: purple;
}
.div4 {
background-color: green;
}
Show Div1
<br/>
Show Div2
<br/>
Show Div3
<br/>
Show Div4
<div class="toggle-container">
<div class="toggle div1"></div>
<div class="toggle div2"></div>
<div class="toggle div3"></div>
<div class="toggle div4"></div>
</div>
EDIT - As per updated question
In order to get this to work with dynamically created elements, you will have to put the var contentDivs = ... inside of the click handler, so you get a live version of that array. Also, you will need to change .querySelector to .querySelectorAll as the former only grabs the first matching element, not all as the latter does.
Here's what the code would look like: (note - I also moved the click handler into an outside function so it was not being recreated for every iteration of the loop, as is good practice)
function clickHandler(event) {
var contentDivs = document.getElementsByClassName("toggle"); // get live set of contentDivs in case any were added dynamically
var trigger = event.target;
var selector = "." + trigger.getAttribute("data-trigger");
var divsToShow = document.querySelectorAll(selector); // grab all matching divs
for (var i = 0; i < contentDivs.length; i++) {
contentDivs[i].style.display = "none";
}
for (var j = 0; j < divsToShow.length; j++) {
divsToShow[j].style.display = "block";
}
}
var toggleControls = document.querySelectorAll("[data-trigger]");
for (var i = 0; i < toggleControls.length; i++) {
toggleControls[i].addEventListener("click", clickHandler);
}
function cloneDiv() {
var elmnt = document.getElementsByClassName("container");
for ( var i=0; i<elmnt.length; i++ ) {
var cln = elmnt[i].cloneNode(true);
}
document.body.appendChild(cln);
document.getElementById("clone").appendChild(cln);
}
window.onload = cloneDiv();

Drag and Drop To Columns with highlighted dragged

I search for Drag And Drop To Columns script and i found this one
http://www.dhtmlgoodies.com/index.html?showDownload=true&whichScript=drag_drop_nodes
I try to add highlighted color on the items which i move
I add css code
<style type="text/css">
.highlight {
background-color: #fff34d;
}
</style>
and modify this in JavaScript
function initDragDropScript() {
dragContentObj = document.getElementById('dragContent');
dragDropIndicator = document.getElementById('dragDropIndicator');
dragDropTopContainer = document.getElementById('dhtmlgoodies_dragDropContainer');
document.documentElement.onselectstart = cancelEvent;;
var listItems = dragDropTopContainer.getElementsByTagName('LI'); // Get array containing all <LI>
listItems.className = 'highlight';
var itemHeight = false;
for (var no = 0; no < listItems.length; no++) {
listItems[no].onmousedown = initDrag;
listItems[no].onselectstart = cancelEvent;
if (!itemHeight) itemHeight = listItems[no].offsetHeight;
if (MSIE && navigatorVersion / 1 < 6) {
listItems[no].style.cursor = 'hand';
}
}
var mainContainer = document.getElementById('dhtmlgoodies_mainContainer');
var uls = mainContainer.getElementsByTagName('UL');
itemHeight = itemHeight + verticalSpaceBetweenListItems;
for (var no = 0; no < uls.length; no++) {
uls[no].style.height = '480 px';
}
var leftContainer = document.getElementById('dhtmlgoodies_listOfItems');
var itemBox = leftContainer.getElementsByTagName('UL')[0];
document.documentElement.onmousemove = moveDragContent; // Mouse move event - moving draggable div
document.documentElement.onmouseup = dragDropEnd; // Mouse move event - moving draggable div
var ulArray = dragDropTopContainer.getElementsByTagName('UL');
for (var no = 0; no < ulArray.length; no++) {
ulPositionArray[no] = new Array();
ulPositionArray[no]['left'] = getLeftPos(ulArray[no]);
ulPositionArray[no]['top'] = getTopPos(ulArray[no]);
ulPositionArray[no]['width'] = ulArray[no].offsetWidth;
ulPositionArray[no]['height'] = ulArray[no].clientHeight;
ulPositionArray[no]['obj'] = ulArray[no];
}
if (!indicateDestionationByUseOfArrow) {
indicateDestinationBox = document.createElement('LI');
indicateDestinationBox.id = 'indicateDestination';
indicateDestinationBox.style.display = 'none';
document.body.appendChild(indicateDestinationBox);
}
}
but it is not working any suggestions

Apply CSS style to child nodes

Here is small fragment to serve as example:
<div id="parentDiv">
<div>child1</div>
<div>child2</div>
</div>
With CSS I can do this:
div#parentDiv { position: absolute; }
div#parentDiv>div { position: relative; }
How to do same styling with javascript?
Try this: (to just have only child elements, not all nested elements)
var pDiv = document.getElementById('parentDiv');
var cDiv = pDiv.children;
for (var i = 0; i < cDiv.length; i++) {
if (cDiv[i].tagName == "DIV") { //or use toUpperCase()
cDiv[i].style.color = 'red'; //do styling here
}
}
Working Fiddle
Not the best one, but you can refer the below: (just for some more knowledge)
Node.prototype.childrens = function(cName,prop,val){
//var nodeList = [];
var cDiv = this.children;
for (var i = 0; i < cDiv.length; i++) {
var div = cDiv[i];
if (div.tagName == cName.toUpperCase()) {
div.style[prop] = val;
//nodeList.push(div);
}
}
// return nodeList;
}
var pDiv = document.getElementById('parentDiv');
pDiv.childrens('div','color','red');
try this
var parentDiv1 = document.getElementById('parentDiv');
var childDiv = parentDiv1.getElementsByTagName('div');
parentDiv.style.position = "absolute";
for (var i = 0; i < childDiv.length; i++) {
childDiv[i].style.position = "relative";
}
You can use the following :
document.getElementById('parentDiv').childNodes[0].style.position = "relative";
document.getElementById('parentDiv').style.position = "absolute";

Script only changes first <p> element

Below is the javascript I have for my page:
window.onmouseover = function(){
var body = document.getElementsByTagName("body")
var h1 = document.getElementsByTagName("h1");
var a = document.getElementsByTagName("a");
var p = document.getElementsByTagName("p")
for(var j = 0; j < p.length; j++) {
body[j].style.fontFamily = "helvetica";
body[j].style.backgroundColor = "rgb(250, 250, 240)"
p[j].style.fontFamily = "courier";
a[j].onclick = function() {
this.style.backgroundColor = "Black"
}
}
}
I have one h1 element, one a element, and 10 p elements. For some reason, this code only changes the font of the first p element, although everything else works fine? Why is this and how can I fix it?
If you have only one a element and (of course) only one body you cannot iterate over 10 of them. This causes an error on the second iteration of the cycle. Use this code instead.
window.onmouseover = function(){
var body = document.getElementsByTagName("body")
var h1 = document.getElementsByTagName("h1");
var a = document.getElementsByTagName("a");
var p = document.getElementsByTagName("p")
body[0].style.fontFamily = "helvetica";
body[0].style.backgroundColor = "rgb(250, 250, 240)"
a[0].onclick = function() {
this.style.backgroundColor = "Black"
}
for (var j = 0; j < p.length; j++) {
p[j].style.fontFamily = "courier";
}
}
It may be generating an error the second time through the loop, since body[1] would be invalid. Move things around so that only manipulations on p are inside the loop.

Categories

Resources