Javascript Add Custom active Class inside loop - javascript

I have two loop like below you can see and need to add a custom active-numberHere class to the first image of each div with a specified number.
for example, if div class number is img-4 so add class active-4 to first img tag.
But I have some problems in code that you can see in the attached image.
in the first div image have the correct class.
but in other div image have extra active like active-4 active-3 and ...!
How can I solve this problem?
// LOOP Create Image Div
let numDiv = 5;
for (k = 0; k < numDiv; k++) {
//Add div area inside Div(products)
let imgPart = `<div class="img-${k} shoe-part"> </div>`;
document.querySelector(".products").insertAdjacentHTML("afterbegin", imgPart);
// LOOP Create Image List Inside Divs
let numImg = 3;
for (j = 0; j < numImg; j++) {
//Add Image List Inside Above Div(shoe-part)
let imgList = `<img class="res-img" src="img/image-${k}.png">`;
document.querySelector(".shoe-part").insertAdjacentHTML("afterbegin", imgList);
}
$('.shoe-part img:first-child').addClass(`active-${k}`);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="products">
</div>

Simple way to do this by jquery is to use html() and prepend() or append()
for add class you can use a simple if statement inside the loop
// LOOP Create Image Div
let numDiv = 5;
for (k = 0; k < numDiv; k++) {
//Add div area inside Div(products)
var DivPart = `<div class="img-${k} shoe-part"></div>`;
// LOOP Create Image List Inside Divs
let numImg = 3;
let ImgPart = '';
for (j = 0; j < numImg; j++) {
//Add Image List Inside Above Div(shoe-part)
var AddClass = (j === 0) ? 'active-'+k : ''; // shorthand if statement to add the class only when j = 0
ImgPart += `<img class="res-img ${AddClass}" src="img/image-${k}.png">`; // add all the images in the valriable ImgPart by using += it means sum/combine/addto
}
DivPart = $(DivPart).html(ImgPart); // update DivPart with the whole div with images in it
$('.products').prepend(DivPart); // prepend the DivPart to the product div
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="products">
</div>

Related

why `card` element is not duplicated 4 times

Why is card element not duplicated 4 times?
function generate4Cards() {
for (var i=0; i < 4; i++) {
var card = document.getElementById('card');
document.body.appendChild(card);
}
}
<body onload="generate4Cards()">
<div id="card">I am a card</div>
</body>
When you call appendChild with an existing element, that element will be removed from its former position in the DOM and appended to the new container. You'll have to explicitly create the div on each iteration instead.
But, having duplicate IDs in a single document is invalid HTML, so probably best to remove the id (or use a class instead):
for (var i = 0; i < 4; i++) {
var card = document.createElement('div');
card.textContent = 'I am a card';
document.body.appendChild(card);
}
Another option is to use cloneNode:
var originalCard = document.querySelector('div');
for (var i = 0; i < 4; i++) {
var card = originalCard.cloneNode(true);
document.body.appendChild(card);
}
<div>I am a card</div>
foo.append(bar) puts bar at the end of foo.
If I put my car at the end of my road, and then put my car at the end of my drive then I don't have two cars.
append only puts bar where you tell it to put it.
It doesn't duplicate it because it isn't supposed to.
Here is the sample code you are looking for -
<html>
<head>
<script>
function generate4Cards() {
for (var i = 0; i < 4; i++) {
var card = document.createElement('div');
card.textContent = 'I am a card';
document.getElementById('cardHolder').appendChild(card);
}
}
</script>
</head>
<body onload="generate4Cards()>
<div id="cardHolder"></div>
</body>
</html>

How to set text of div to its Id in javascript

what I am trying to achieve is set the text of a div tag to the name if its ID from javascript. I have tried this;
mydiv.getElementsByClassName("divDesign").innerHTML = document.getElementsByClassName("divDesign").getElementById;
However, this returns undefined in the div tag instead of writing its id.
Using getAttribute() method:
For the first div with ClassName = 'divDesign':
document.getElementsByClassName('divDesign')[0].innerHTML = document.getElementsByClassName('divDesign')[0].getAttribute('id');
For all divs with ClassName = 'divDesign':
var mydivs = document.getElementsByClassName('divDesign');
for (var index = 0; index < mydivs.length; index++) {
mydivs[index].innerHTML = mydivs[index].getAttribute('id');
}
<div class="divDesign" id="someId"></div>
Using id() property:
For the first div with ClassName = 'divDesign':
document.getElementsByClassName('divDesign')[0].innerHTML = document.getElementsByClassName('divDesign')[0].id;
For all divs with ClassName = 'divDesign':
var mydivs = document.getElementsByClassName('divDesign');
for (var index = 0; index < mydivs.length; index++) {
mydivs[index].innerHTML = mydivs[index].id;
}
<div class="divDesign" id="someId"></div>
Documentation:
MDN
Yo need to specify an index of the element as document.getElementsByClassName("divDesign") returns a nodes list.
document.getElementsByClassName("divDesign")[0].innerHTML =
document.getElementsByClassName("divDesign")[0].id;
<div class="divDesign" id="iAmAnId"></div>

I'm trying to make a div width expand once clicking on another div

Im trying to make a div expanded once you click on another div. In my case I'm try to make div with some text in it expand when the image is clicked. A link to my JSFiddle - https://jsfiddle.net/txoyuvqn/3/
My javascript that I am using looks like.
var divs = document.getElementsByClassName('image');
var whattochange = document.getElementsByClassName('text');
for (var i = 0; i < divs.length; i++)
divs[i].addEventListener("click", function () {
for (var i = 0; i < whattochange.length; i++) {
whattochange[i].style.width = '500px'
whattochange[i].style.transition = 'all 1s'
whattochange[i].style.backgroundColor = 'red'
}
}, false);
However when I click on the class called image it effects all the Text classes, i know it's because were changing the css to all of the text divs, however is there a way to make it only effect the correlating div? Or am I going about creating this in the wrong way?
getElementsByClassName returns an array, not a single element.
divs is an array, and you are correctly using a for loop and the index indicator [i] after your variable name divs.
You need a similar for loop for whattochange.
var divs = document.getElementsByClassName('image');
var whattochange = document.getElementsByClassName('text');
for (var i = 0; i < divs.length; i++)
divs[i].addEventListener("click", function () {
for (var i = 0; i < whattochange.length; i++) {
whattochange[i].style.width = '800px';
whattochange[i].style.transition = 'all 1s';
whattochange[i].style.backgroundColor = 'red';
}
}, false);
There may be a better way, but you could do it like this:
var divs = document.getElementsByClassName('image');
var whattochange = document.getElementsByClassName('text');
for (var i = 0; i < divs.length; i++)
{
divs[i].addEventListener("click", function()
{
var w = document.getElementById(this.id.replace('img', 'text'));
w.style.width = '800px'
w.style.transition = 'all 1s'
w.style.backgroundColor = 'red'
});
whattochange[i].id = 'text' + i;
divs[i].id = 'img' + i;
}
See the fiddle
Javascript
var divs = document.getElementsByClassName('image');
var whattochange = document.getElementsByClassName('text');
for (var i = 0; i < divs.length; i++) {
divs[i].addEventListener("click", function () {
for (var i = 0; i < whattochange.length; i++) {
whattochange[i].style.width = '800px';
whattochange[i].style.transition = 'all 1s';
whattochange[i].style.backgroundColor = 'red';
}
}, false);
}
You have to be sure that the elements exist if your JavaScript code depends on them. The reason why your fiddle didnt work was because, you was not loading the script after the body has finished loading.
In your code, One way of achieving this is by putting the <script> tag at the end of the body like this:
<html>
<head></head>
<body>
<script type="text/javascript">
// code here
</script>
</body>
You can also put all your code in a function for the window.onload event or use jQuery.

Delete Javascript generated HTML

I am programming a blackjack game and for each drawn card i create a tag <img> to display the card.
Naturally i have to delete this tag <img> after every game, but how can i do this?
Is there a way that I can remove all <img> tags within a parent?
Is there something like this: (Pseudecode)
div.removeAllChildElemtens()
or
div.removeChildElements("img");
Thanks.
If you create the elements using document.createElement('img') then you can keep a reference to them in order to delete them later.
var cards = [];
for (var i = 0; i < 52; i++)
{
var card = document.createElement('img');
// ... more initialisation of card
cards.push(card);
}
// later, to remove all
for (var i = 0; i < cards.length; i++)
{
var card = cards[i];
card.parentElement.removeChild(card);
}
Please, see the removeChild usage trick or use the new remove() function:
var div = document.getElementById("parentDivId");
var images = div.getElementsByTagName('img');
for(var i = 0; i < images.length; i++){
var img = images[i];
img.parentNode.removeChild(img);
//OR img.remove() as #Pete TNT pointed-out for modern web-browsers (FF/CH < 23)
}

Is it really necessary to use array, to display an innerHTML of a complete node list after child remove?

This code works well but when I start to remove nodes the complete list disappear and I'm left with one node in the innerHTML, instead of removing one by one gradually which is what I want. To leave a few to none behind perhaps gradually instead of straight one for all displayed in the innerHTML, of the div that displays the removal sort of say... I can perfectly do this to work using arrays but I'm curious if there's an way out without using any(arrays)?
HTML code
<button onClick="remov()">remove</button>
<button onClick="addDiv()">Add Div</button>
<div>
<div></div>
<div></div><div></div>
<div></div>
</div>
<div id="tt"></div>
Javascript Code
var stage = document.getElementsByTagName("div")[0];
var tt = document.getElementById("tt");
function remov() {
if (stage.hasChildNodes()) {
stage.removeChild(stage.firstChild);
for (var i = 0; i < stage.childNodes.length; i++) {
tt.innerHTML = stage.childNodes[i].nodeName;
}
if (!stage.hasChildNodes()) {
tt.innerHTML = "no nodes";
}
}
}
for (var i = 0; i < stage.childNodes.length; i++) {
tt.innerHTML += stage.childNodes[i].nodeName;
}
function addDiv() {
var a = document.createElement("div");
stage.appendChild(a);
if (!stage.hasChildNodes()) {
tt.innerHTML += stage.firstChild.nodeName;
} else {
tt.innerHTML += stage.lastChild.nodeName
}
}
jsfiddle
If you want to display all divs during their removal need to change = to += as below
function remov() {
tt.innerHTML=''; //EDIT forgot to add in this line
if (stage.hasChildNodes()) {
stage.removeChild(stage.firstChild);
for (var i = 0; i < stage.childNodes.length; i++) {
tt.innerHTML += stage.childNodes[i].nodeName; //<------- + needed to display all divs
}
if (!stage.hasChildNodes()) {
tt.innerHTML = "no nodes";
}
}
}
EDIT Fiddle added

Categories