Javascript loop for every 2 classes - javascript

Hi I've got a small issue but not sure how to solve it by javascript/jquery. Essentially ive got several div classes but what i want to do is to create a loop to add a class on certain divs, without having to add an id on them manually but to add a id or class through the javascript code.
Heres an idea of what i mean:
<div></div><div></div>
<div></div><div></div>
<div></div><div></div>
<div></div><div></div>
This is what i currently have so lets say two divs will be a row. I want it so a a class is added in a certain way to make it like this:
<div class="green"></div> <div></div>
<div></div> <div class="green"></div>
<div class="green"></div> <div></div>
<div></div> <div class="green"></div>
So i am guessing it will be some sort of loop for every 2 divs then it will repeat in reverse.

using jquery
Use this loop to add class after 2 div
DEMO
$('div').each(function(i){
if((i%3) === 0){
$(this).addClass('green')
}
});
using :odd and :even selector
DEMO
$( "div:odd" ).addClass( "green" );
for even
$( "div:even" ).addClass( "green" );

Basically you want Zig-Zag.
There is no need of loops. You can use :nth-child selector as follow:
$('div:nth-child(4n+1)').addClass('green'); // Selects 1, 5, 9, 13, ...
$('div:nth-child(4n)').addClass('green'); // Selects 4, 8, 12, 16, ...
Demo
Here is the pure CSS Demo.
body {
width: 120px;
}
div {
height: 50px;
width: 50px;
background: red;
margin: 5px;
float: left;
}
div:nth-child(4n+1) {
background: green;
}
div:nth-child(4n) {
background: green;
}
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>

HTML:
<div class="wrapper">
<div class="element">1</div>
<div class="element">2</div>
<div class="element">3</div>
<div class="element">4</div>
<div class="element">5</div>
<div class="element">6</div>
</div>
Pure Javascript:
var parents = document.getElementsByClassName("wrapper");
for (var i = 0, ii = parents.length; i < ii; i++) {
var parent = parents[i],
children = parent.children;
for (var j = 0, jj = children.length; j < jj; j++) {
var elem = children[j];
if (j % 2 === 0) {
elem.classList.add("highlight");
}
}
}
Demo
OR
jQuery:
$(".element:odd").addClass("highlight");
Demo

If just for show different background, you may use css nth-child(even) or nth-child(odd), as should sample in the table:
tr:nth-child(even) {background: #CCC}
tr:nth-child(odd) {background: #FFF}

You can grab your divs with a for loop using childNodes () javascript function. If the index is odd then you can apply manually your class.
something like this:
var nodes = parentElement.childNodes();
for (var i = 0; i < nodes.length; i++) {
if (i % 2 == 0) continue;
nodes[i].className = "green";
}

Related

How to add CSS styling from Javascript

Quick disclaimer - I'm new to coding and JavaScript, and this is my first post so please go easy on me.
I have an array of Hex codes for colors and I want to use JQuery to style some empty div's in the HTML with the colors. The div's have a class of "square" and sit inside a main tag and have been given a height and width in CSS so I know they are there. I want to attach the array in order so the div's are colored in order.
This is my HTML:
<main>
<div class="Sample">
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
</div>
</main>
and this is the array:
let colors = ['#7e6493', '#895782', '#944a71', '#9f3c60', '#aa2f4f']
let $gameSquares = $('.square');
So ideally what I wanted was a function which changed the background colour of the div's one by one with the Hex colors from the array.
Thanks in advance.
Please clarify your question, if you only want to give this background-color property for square class you can use this pure CSS solution with pseudoclass :nth-child(an+b):
square:nth-child(1){ #7e6493 };
square:nth-child(2){ #895782 };
square:nth-child(3){ #944a71 };
square:nth-child(4){ #9f3c60 };
square:nth-child(5){ #aa2f4f };
more about nth-child from MDN docs
You can use this code:
let colors = ['#7e6493', '#895782', '#944a71', '#9f3c60', '#aa2f4f']
$('.square').each(function(index, element){
$(element).css("background-color", colors[index]);
})
let colors = ['#7e6493', '#895782', '#944a71', '#9f3c60', '#aa2f4f']
let $gameSquares = $('.square');
$gameSquares.each(function(idx, el) {
$(el).css('backgroundColor', colors[idx]);
});
.square
{
width: 50px;
height: 50px;
float: left;
border: 1px solid #000;
margin: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<main>
<div class="Sample">
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
</div>
</main>
colors = ['#7e6493', '#895782', '#944a71', '#9f3c60', '#aa2f4f'];
i = 0;
totalColors = colors.length;
$('.square').each( function(){
$(this).css('backgroundColor', colors[i]);
if (i >= totalColors){
i = 0;
} else {
i++;
}
});
Try this:
var colorSquares = function( $squares, colors ) {
$squares.each( function( i ) {
if ( colors[ i ] ) {
$( this ).css( 'background-color', colors[ i ] );
}
} );
}
colorBoxes( $gameSquares, colors );
You need to deal with children() method and first() child method then use it together like this:
$(document).ready(function() {
var colors = ['#7e6493', '#895782', '#944a71', '#9f3c60', '#aa2f4f']
var i = 0;
// Getting first square
var $tempSquare = $('.sample').children().first();
// console.log($tempSquare);
while ($tempSquare.length && colors[i]) {
// Changing current square background color
$tempSquare.css("background-color", colors[i]);
// Move to next sibling
$tempSquare = $tempSquare.next();
// console.log($tempSquare);
// Increment index
i++;
}
});

Tie children of one div to children of another div with jquery

I have two parent divs: .inputs and .infoBoxes. Each of them have an equal number of children. When the user clicks into the first .input in .inputs, the first .infoBox in .infoBoxes should slideDown(). Same for second, third, etc. I'd like to do this without re-writing the same code for each pair. So far I have:
var $inputs = $('.inputs').children();
var $infoBoxes = $('.infoBoxes').children();
for(var i = 0; i < $inputs.length; i++ ) {
$($inputs[i]).find('.input').focus(function() {
$($infoBoxes[i]).slideDown();
})
$($inputs[i]).find('.input').blur(function() {
$($infoBoxes[i]).slideUp();
})
}
This isn't working but I have tried replacing i with the indexes of each div.
$($inputs[0]).find('.input').focus(function() {
$($infoBoxes[0]).slideDown();
})
$($inputs[0]).find('.input').blur(function() {
$($infoBoxes[0]).slideUp();
})
repeat...
repeat...
repeat...
This works but isn't very DRY. I'm looking for a better solution that won't have me repeating a bunch of code.
First code will not work, because you using same variable for all internal functions. You should wrap it into function, which will create local variable for index. Try following code:
var $inputs = $('.inputs').children();
var $infoBoxes = $('.infoBoxes').children();
for(var i = 0; i < $inputs.length; i++ ) {
(function(ix) {
$($inputs[ix]).find('.input').focus(function() {
$($infoBoxes[ix]).slideDown();
})
$($inputs[ix]).find('.input').blur(function() {
$($infoBoxes[ix]).slideUp();
})
})(i);
}
slideDown is used for showing elements. I am guessing you want to hide elements, since you are clicking on them and you cant click an hidden element. Use hide or slideUp to hide elements.
$(".input, .infobox").on("click", function() {
var ind = $(this).index();
$(".infobox:eq(" + ind + "), .input:eq(" + ind + ")").hide(500);
});
.input,
.infobox {
widht: 100%;
height: 50px;
text-align: center;
margin: 5px 0;
color: white;
}
.input {
background: red;
}
.infobox {
background: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="inputs">
<div class="input">1</div>
<div class="input">2</div>
<div class="input">3</div>
<div class="input">4</div>
<div class="input">5</div>
</div>
<div class="infoboxes">
<div class="infobox">1</div>
<div class="infobox">2</div>
<div class="infobox">3</div>
<div class="infobox">4</div>
<div class="infobox">5</div>
</div>

Add class to an element without an id

I have a list of items:
<div class="crew-item>
<div class="crew-grid"></div>
<div class="crew-detail></div>
</div>
<div class="crew-item>
<div class="crew-grid"></div>
<div class="crew-detail></div>
</div>
<div class="crew-item>
<div class="crew-grid"></div>
<div class="crew-detail></div>
</div>
When I click on a selected 'crew-grid' I'd like to add a class ('active') to its 'crew-item' parent, but I have no idea how to achieve that using vanilla js or jQuery.
The goal is to reveal the 'crew-detail' part, with active class added to its parent.
Like this?:
$('.crew-grid').on('click', function () {
$(this).closest('.crew-item').addClass('active');
});
Basically, starting from the clicked element, get the closest ancestor element which matches that selector. You don't need an id to target an element, just a way to identify it based on the information you have (in this case the clicked element).
If you want to de-activate other elements at the same time:
$('.crew-grid').on('click', function () {
$('.crew-item').removeClass('active');
$(this).closest('.crew-item').addClass('active');
});
Using jQuery :
$('.crew-grid').click(function() {
$(this).closest('.crew-item').addClass('active');
});
Use Document.querySelectorAll()
var crews = document.querySelectorAll('.crew-item');
if (crews) {
for (var i = 0; i < crews.length; i++) {
var grid = crews[i].querySelector('.crew-grid');
grid.addEventListener('click', toggleActive, false);
}
}
function toggleActive() {
var grids = document.querySelectorAll('.crew-item');
for (var i = 0; i < grids.length; i++) {
if (grids[i].classList.contains('active')) {
grids[i].classList.remove('active');
}
}
this.parentNode.classList.add('active');
}
.crew-item.active {
background: #DDD;
}
.crew-grid:hover {
cursor: pointer;
background: #eee;
}
<div class="crew-item active">
<div class="crew-grid">crew-grid</div>
<div class="crew-detail">crew-detail</div>
</div>
<br>
<div class="crew-item">
<div class="crew-grid">crew-grid</div>
<div class="crew-detail">crew-detail</div>
</div>
<br>
<div class="crew-item">
<div class="crew-grid">crew-grid</div>
<div class="crew-detail">crew-detail</div>
</div>

How to target individual div & apply class or attribute id

How can i select each div inside parent div & apply class (om_0 & go on) with increasing index number. Here I am unable to target each div.
Or how can I add attribute id="om_0", id="om_1", id="om_2" etc. to each div
The problem is it's applying all classes in one div & repeat it
var cirLength = $("div#circleBox > div").length;
for(var i=0; i<cirLength; i++){
$("div#circleBox").find('div').addClass('om_'+i);
}
<div id="circleBox"><div class="om_0 om_1 om_2"><span>AcessGreen</span></div><div class="om_0 om_1 om_2"><span>AccessBlue</span></div><div class="om_0 om_1 om_2"><span>AccessOrange</span></div></div>
You can use each() to iterate jQuery objects
$("div#circleBox").find('div').each(function(i) {
$(this).addClass('om_' + i);
// If you need to add it as id then use `this.id= 'om_' + i ` instead of `$(this).addClass('om_' + i)`
});
.om_0 {
color: red;
}
.om_1 {
color: green;
}
.om_2 {
color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="circleBox">
<div><span>AcessGreen</span>
</div>
<div><span>AccessBlue</span>
</div>
<div><span>AccessOrange</span>
</div>
</div>
With your own code you need to select individual item using eq()
var cirLength = $("div#circleBox > div").length;
for (var i = 0; i < cirLength; i++) {
$("div#circleBox").find('div').eq(i).addClass('om_' + i);
}
.om_0 {
color: red;
}
.om_1 {
color: green;
}
.om_2 {
color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="circleBox">
<div><span>AcessGreen</span>
</div>
<div><span>AccessBlue</span>
</div>
<div><span>AccessOrange</span>
</div>
</div>

Changing class of elements

I want to set up floating elements in a way it would depend of their amount.
<div id="whatever">
<div class="iwantthischangedto3elements">
element 1
element 2
element 3
</div>
<div class="iwantthischangedto2elements">
element 1
element 2
</div>
</div>
I can't really figure how to do this.
I'm guessing javascript is the answer, but can't get it work :
<script type="text/javascript">
function f() {
var list = document.getElementById("whatever");
var nbofelements = whatever.getElementsByTagName("a").length;
return nbofelements ;
whatever.getElementsByTagName("div").className += "elements + nbofelements";
}
</script>
Thanks for helping, I really struggle with javascript...
Edit:
Thanks all for your answers.
Sorry i didn't make myself clear enough, english isn't my first language.
Tambo did get what I meant, code works great.
However there's something I forgot...
An "h1" can be sometimes placed before the "a" list, and should not be counted as an element. Possibly other "h2", "h3", and so on... I want to count only "a" elements...
<div id="whatever">
<div class="iwantthischangedto3elements">
<h1>Do no not count this</h1>
element 1
element 2
element 3
</div>
Any idea how to proceed ?
Cheers
Vincent
You can use the for loop and Element.classList to add class
var whateverChild = document.querySelectorAll("#whatever div");
for(var i = 0; i < whateverChild.length; i++) {
//var anchor = document.querySelectorAll(whateverChild);
if(whateverChild[i].childElementCount == 2){
whateverChild[i].classList.add("two")
}else if(whateverChild[i].childElementCount == 3){
whateverChild[i].classList.add("three")
}
}
.two a{color: green}
.three a{color: red}
<div id="whatever">
<div class="iwantthischangedto3elements">
element 1
element 2
element 3
</div>
<div class="iwantthischangedto2elements">
element 1
element 2
</div>
</div>
If you have a paragraph in it you can use this
var whateverChild = document.querySelectorAll("#whatever div");
for(var i = 0; i < whateverChild.length; i++) {
var anchorLength = whateverChild[i].querySelectorAll("a").length;
if(anchorLength == 2){
whateverChild[i].classList.add("two")
}else if(anchorLength == 3){
whateverChild[i].classList.add("three")
}
}
.two a{color: green}
.three a{color: red}
<div id="whatever">
<div class="iwantthischangedto3elements">
element 1
<p> i am a paragraph </p>
element 2
element 3
</div>
<div class="iwantthischangedto2elements">
element 1
element 2
</div>
</div>
You can reduce the code to this
var numbersArray = ["zero", "one", "two", "three", "four", "five"],
whateverChild = document.querySelectorAll("#whatever div");
for(var i = 0; i < whateverChild.length; i++) {
var anchorLength = whateverChild[i].querySelectorAll("a").length;
whateverChild[i].classList.add(numbersArray[anchorLength])
}
.zero{color: orange}
.one{color: blue}
.two a{color: green}
.three a{color: red}
.four{color: purple}
.five{color: beige;}
<div id="whatever">
<div class="iwantthischangedto3elements">
element 1
<p> i am a paragraph </p>
element 2
element 3
</div>
<div class="iwantthischangedto2elements">
element 1
element 2
</div>
</div>

Categories

Resources