Javascript: Changing the class of the first element in a div - javascript

i'm trying to change the class of the first div.
e.g.
var div1 = element.getElementsByClassName("parent")
div1.children[0].setAttribute("class", "1 2");
<div class="parent">
<div class="1">Test</div>
<div class="1">test</div>
<div class="1">test</div>
</div>
But class doesnt change. Any idea why?
thanks :)

Change it to:
div1.children[0].className = "1 2";
Or
div1.children[0].classList.add('1');
div1.children[0].classList.add('2');
You should pick better class names btw!
Edit:
var div1 = document.getElementsByClassName("parent")[0];
div1.children[0].classList.add('1');
div1.children[0].classList.add('2');

Jquery way:
$(".parent > div:first").addClass("1 2");

// getElementsByClassName return an array (it is a collection)
var allDivs = document.getElementsByClassName("root");
// in the array i need the first
var myFirstElement = allDivs[0];
// i want first child
var myFirstChild = myFirstElement.children[0];
myFirstChild.className = 'b' ;
.a{ border : solid 1px red }
.b{ border : solid 1px blue }
<div class="root">
<div class="a">Test</div>
<div class="a">test</div>
<div class="a">test</div>
</div>

Related

change properties of two divs with one onclick and querySelectorAll()

I have multiple elements that are seperatet in two divs. The first div contains a Text and the second div a color.
When I click on one element the text and color should change and if I click it again it should change back.
The problem is that no matter which one I click, its always the last one which changes.
The HTML part:
<style>
.colorGreen {
background-color: green;
}
.colorRed {
background-color: red;
}
</style>
<div class="box2">Text1</div>
<div class="box1 colorGreen">O</div>
<div class="box2">Text1</div>
<div class="box1 colorGreen">O</div>
<div class="box2">Text1</div>
<div class="box1 colorGreen">O</div>
The JavaScript part:
<script type='text/javascript'>
var box1Temp = document.querySelectorAll(".box1");
var box2Temp = document.querySelectorAll(".box2");
for (var i = 0; i < box1Temp.length; i++) {
var box1 = box1Temp[i];
var box2 = box2Temp[i];
box2.onclick = box1.onclick = function() {
if (box1.classList.contains("colorGreen")) {
box1.classList.add("colorRed");
box1.classList.remove("colorGreen");
box2.innerHTML = "Text2";
} else {
box1.classList.add("colorGreen");
box1.classList.remove("colorRed");
box2.innerHTML = "Text1";
}
}
}
</script>
It works, when I use only one div.
Then I can use 'this', instead of the 'box1' variable, to addres the right element.
But if I replace 'box1' with 'this' its still the text div that changes.
(I know it's obvious that this is happening, but I'm lost)
With a few small tweaks, this can be written a lot more cleanly:
// Capture click event for parent container, .toggle-set
for (const ele of document.querySelectorAll(".toggle-set")) {
ele.addEventListener("click", function() {
// Grab text and color elements
const textToggle = ele.querySelector(".toggle-text");
const colorToggle = ele.querySelector(".toggle-color");
// Toggle text
// NOTE: This could use further refinement with regex or something similar to strip whitespace before comparison
textToggle.textContent = textToggle.textContent == "Text1" ? "Text2" : "Text1";
// Toggle css classes
colorToggle.classList.toggle("colorGreen");
colorToggle.classList.toggle("colorRed");
});
}
.colorGreen { background-color: green; }
.colorRed { background-color: red; }
<div class="toggle-set">
<div class="toggle-text">Text1</div>
<div class="toggle-color colorGreen">
O
</div>
</div>
<div class="toggle-set">
<div class="toggle-text">Text1</div>
<div class="toggle-color colorGreen">
O
</div>
</div>
Your code is so confused
You were right for the this option.
you can do with simple onclick function :
function change(el){
box1 = el.querySelector('.box1');
box2 = el.querySelector('.box2');
if (box1.classList.contains("colorGreen")) {
box1.classList.add("colorRed");
box1.classList.remove("colorGreen");
box2.innerHTML = "Text2";
} else {
box1.classList.add("colorGreen");
box1.classList.remove("colorRed");
box2.innerHTML = "Text1";
}
}
<style>
.colorGreen {
background-color: green;
}
.colorRed {
background-color: red;
}
</style>
<div onclick="change(this)">
<div class="box2">Text1</div>
<div class="box1 colorGreen">O</div>
</div>
<div onclick="change(this)">
<div class="box2">Text1</div>
<div class="box1 colorGreen">O</div>
</div>
<div onclick="change(this)">
<div class="box2">Text1</div>
<div class="box1 colorGreen">O</div>
</div>
I think following code snippet would help you to get your desired result
let box1 = document.querySelectorAll(".box1");
let box2 = document.querySelectorAll(".box2");
box1.forEach((b1,i) => {
b1.addEventListener("click",(ev) => {
ev.target.classList.toggle("colorGreen");
ev.target.classList.toggle("colorRed");
console.log(box2[i]);
if(ev.target.classList.contains("colorGreen")){
box2[i].textContent = "Text1";
}else{
box2[i].textContent = "Text2"
}
})
})

Jquery append while wrapping every x element

I'm trying to create HTML like this:
<div class="container">
<div class="wrap">
<div class="el"></div>
<div class="el"></div>
<div class="el"></div>
</div>
<div class="wrap">
<div class="el"></div>
<div class="el"></div>
<div class="el"></div>
</div>
<div class="wrap">
<div class="el"></div>
<div class="el"></div>
<div class="el"></div>
</div>
</div>
The component used to add el element:
<input type="text" name="elements" />
el elements will appended to the container based on what number is added in the input. Every 3 elements should be wrapped in wrap div.
What I have so far:
$("input[name=elements]").on("keydown keyup", function() {
var amount = parseInt($(this).val());
for(i = 0; i < amount; i++) {
$(".container").append('<div class="el"></div>');
}
});
It adds the el divs but I'm not sure how to simultaneously wrap every 3 in wrap. Also is it possible to also remove el divs? If say I first type 8 in the input then I type 3, 11 divs will be added instead having just 3. In other words, the number of el divs in the HTML should alway be equal to the number in the input value. Would it make sense just to clear out the HTML first every time on input type?
You could first create an array of elements based on number of input value, append it to container and then wrap every nth element into wrap element.
const container = $('.container')
$("input").on('keyup', function() {
const val = parseInt($(this).val()) || 0;
const html = Array.from(Array(val), () => (
$("<div>", {
'class': 'el',
'text': 'element'
})
))
container.html(html)
for (let i = 0; i < val; i += 3) {
container
.find('.el')
.slice(i, i + 3)
.wrapAll("<div class='wrap'></div>");
}
})
.wrap {
border: 1px solid green;
margin: 10px 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text">
<div class="container"></div>

get element by id - using variable

I'm trying to use the function getElementById().
I have several ID's that i want to change style of, one by one, in an increasing order. I have a variable called numberOfTimes, which increases with 1 every time.
The names of the ID's are 1, 2, 3, 4 etc, and up to 8.
Is there some way I can use the variable-name in the function - if not, how should you solve this?
var numberOfTimes = 1;
document.getElementById(1).style.backgroundColor = "green";
Let's pretend your IDs look like this idx (x stands for the number). You can do:
var numberOfTimes = 8;
for (var i = 1; i <= numberOfTimes; ++i) {
document.getElementById('id' + i).style.backgroundColor = "green";
}
Solution if you really specific to change the color of the element one by one. Then you can use for loop.
second
document.getElementById(1)
You can use integer value directly but preferable you should use id with some text.
just use like this in for loop
for(var i=1;i<=8;i++){
document.getElementById("div_"+i).style.backgroundColor = "green";
}
As stated in other answers and comments, it is highly recommended not to use numbers only as IDs, also you can pick these divs upon a unique class name which will get you an array of them, and just loop through the array just like in this fiddle.
However here's the code JS Fiddle
var id = 1;
changeBG();
function changeBG() {
document.getElementById('el-' + id).style.backgroundColor = "green";
id++;
var t = setTimeout(changeBG, 500);
}
div {
width: 100%;
height: 50px;
margin-bottom: 5px;
display: inline-block;
}
<div id="el-1"></div>
<div id="el-2"></div>
<div id="el-3"></div>
<div id="el-4"></div>
<div id="el-5"></div>
<div id="el-6"></div>
<div id="el-7"></div>
<div id="el-8"></div>
Numbers-only ID are not a good practice, I hope this quetion is in the purpose of learning.
for(var i = 1; i < 9; i++){
document.getElementById(i).style['background'] = 'green';
}
div {
width:100%;
height:20px;
margin-bottom:10px;
}
<div id="1"></div>
<div id="2"></div>
<div id="3"></div>
<div id="4"></div>
<div id="5"></div>
<div id="6"></div>
<div id="7"></div>
<div id="8"></div>

Change child element of array item (syntax)

I have a few divs which are using the same class.
Inside the divs are three more divs with identical classes.
<div class="plane">
<div class="win1">Lorem ipsum</div>
<div class="win2">Dolor sit</div>
<div class="win3">amet.</div>
</div>
<div class="plane">
<div class="win1">Lorem ipsum</div>
<div class="win2">Dolor sit</div>
<div class="win3">amet.</div>
</div>
var allPlanes = $('.plane');
for (var i = 0; i < allPlanes.length; i++) {
var onePlane = allPlanes[i];
var baseHeight = 10;
$(onePlane + " .win1").css("height", parseInt(baseHeight*1));
$(onePlane + " .win2").css("height", parseInt(baseHeight*2));
$(onePlane + " .win3").css("height", parseInt(baseHeight*3));
}
(Don't mind about the names. It's just an example...)
Now I made an array with the outside divs and I can select the single divs inside. But I did not get the right syntax for the child divs inside.
Can anyone help?
My Fiddle: http://jsfiddle.net/SchweizerSchoggi/559xvww6/
Change you script to this:
var allPlanes = $('.plane');
var baseHeight = 10;
$(".plane > .win1").css("height", parseInt(baseHeight*1)+"px");
$(".plane > .win2").css("height", parseInt(baseHeight*2)+"px");
$(".plane > .win3").css("height", parseInt(baseHeight*3)+"px");
You don't need the for loop in such a case.
A prettier way:
var baseHeight = 10;
for (var i = 1; i <= 3; i++) {
$(".plane > .win"+i).css("height", parseInt(baseHeight*i)+"px");
}
http://jsfiddle.net/559xvww6/3/
If you don't want to use a for loop and want to dinamically configure from an array:
var baseHeight = 10;
$.map([1,2,3], function(i) {
$(".plane > .win"+i).css("height", parseInt(baseHeight*i)+"px");
});
http://jsfiddle.net/559xvww6/10/
Edit:: Just a side note: all these approachs are valid, but that doesn't mean that they are the best / most efficient ones. Feel free to use the one you like the most, understand it and try to use it or adapt it to your very personal situation. The "easiest" approach is surely the first one, but it is also the longest one.
isn't this one is better:
var base = 10;
$('.plane > div').css('height', function(){
return base*($(this).index()+1)
});
.plane {
background-color: #ccc;
border: solid 1px #cdcdcd;
margin-bottom: 15px;
}
.plane > .win1 { background-color: #ddd; }
.plane > .win2 { background-color: #eee; }
.plane > .win3 { background-color: #fff; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="plane">
<div class="win1">Lorem ipsum</div>
<div class="win2">Dolor sit</div>
<div class="win3">amet.</div>
</div>
<div class="plane">
<div class="win1">Lorem ipsum</div>
<div class="win2">Dolor sit</div>
<div class="win3">amet.</div>
</div>
You cannot use + operator between a jQuery object and a string.
The correct way to do it is this:
$(".win1", onePlane).css("height", parseInt(baseHeight*1));
$(".win2", onePlane).css("height", parseInt(baseHeight*2));
$(".win3", onePlane).css("height", parseInt(baseHeight*3));
Each of these queries translates to: select all elements with .winX that are inside the jQuery object onePlane.
I would use all the same class names inside the nest and then just do $('.plane:eq(0) .win:eq(2)').html()
alert( $('.plane:eq(0) .win:eq(2)').html() );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="plane">
<div class="win">Lorem ipsum</div>
<div class="win">Dolor sit</div>
<div class="win">amet.</div>
</div>
<div class="plane">
<div class="win">Lorem ipsum</div>
<div class="win">Dolor sit</div>
<div class="win">amet.</div>
</div>
if your classes are fixed then you can do with this code
$(".win1", $(".plane")).css("height", parseInt(baseHeight*1));
$(" .win2", $(".plane")).css("height", parseInt(baseHeight*2));
$(" .win3", $(".plane")).css("height", parseInt(baseHeight*3));
You can do using each loop of plane class.
$('.plane').each(function(){
baseHeight = 10;
$(this).find(".win1").css("height", parseInt(baseHeight*1));
$(this).find(".win2").css("height", parseInt(baseHeight*2));
$(this).find(".win3").css("height", parseInt(baseHeight*3));
});
Demo

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