Reputation: 61
i want to click on button , transfer class name that have the color from the active element to next one.
this not real task i just learn but i blocked
var el = document.getElementById('one');
var boxDiv = document.getElementsByClassName('.box');
var btnCh = document.getElementById('changeColor');
btnCh.onclick = function() {
if (boxDiv.classList.contains('green')) {
boxDiv.nextSiblings.classList.add('green');
boxDiv.previousSiblings.classList.add('green');
}
}
<div class="row">
<div class="box"><span>1</span></div>
<div class="box green" id="one"><span>2</span></div>
<div class="box "><span>3</span></div>
<div class="box"><span>4</span></div>
</div>
<div class="row">
<button id="changeColor">add class</button>
</div>
https://codepen.io/hesham-farag/pen/MZLxeM
Upvotes: 0
Views: 1069
Reputation: 111
You have to create some logic here. If you want to have one colored box from list of all, you have to remember your previous main box. So, you'll write next instructions:
html:
<div class="row">
<div class="box main"><span>1</span></div>
<div class="box green" id="one" ><span>2</span> </div>
</div>
<button>Change main box</button>
js:
let boxes = Array.from(document.querySelectorAll(".box"));
let button = document.getElementsByTagName('button')[0];
let mainBoxIndex = 0;
button.addEventListener('click', function() {
boxes[mainBoxIndex].classList.remove('main');
mainBoxIndex = (mainBoxIndex + 1 < boxes.length) ? mainBoxIndex + 1 : 0;
boxes[mainBoxIndex].classList.add('main');
});
Get closer look you can here: https://codepen.io/anon/pen/jXJyqQ Hope it'll help you a bit.
Upvotes: 1
Reputation: 34556
There are several issues with your code (always check the console for errors).
Firstly, understand the difference between a node and a nodeset. Functions like getElementsByClassName
return a nodeset, which is an array-like collection of nodes. You therefore cannot run node methods on them as you are, i.e. this will cause an error:
boxDiv.nextSiblings(... //boxDiv is not a node; it's a nodeset
Therefore, you need to loop over the nodeset and deal with each element in turn.
Next, nextSiblings
and previousSiblings
are not valid methods; they should be in the singular, not plural.
Next, you're assuming there's a next and previous sibling. This will error on the first and last .box
div for obvious reasons.
Also, while we're here:
.onclick
and instead use addEventListener()
. There are several reasons for this that are beyond the scope of this answer.let
than var
Let's pull it all together
let
parent = document.querySelector('#row'),
boxDiv = document.querySelectorAll('.box'),
btnCh = document.querySelector('#changeColor')
;
btnCh.addEventListener('click', evt => {
boxDiv.forEach(el => {
if (el.classList.contains('green')) {
if (el.nextSibling) el.nextSibling.classList.add('green');
if (el.previousSibling) el.previousSibling.classList.add('green');
}
});
}, false);
Upvotes: 1