user3409230
user3409230

Reputation: 13

Children of children Javascript DOM

Say I had a div with two children divs that acted as columns for an undefined number of navigation buttons. Such as

<div id='controls'>
<div id='column1'><a id='button1' href=#></a></div>
<div id='column2'><a id='button2' href=#></a></div>
</div>

I currently have it like so

var column1 = document.getElementById('column1').children;
var column2 = document.getElementById('column2').children;
var button1 = document.getElementById('button1');

button1.onclick = function() {
    column1.className = column1.className.replace(new RegExp('\b' + active + '\b'),'');
    column2.className = column2.className.replace(new RegExp('\b' + active + '\b'),'');
    this.className += ' active';
};

Since I'm doing the same thing to both, is there a way to combine it to be something along the lines of:

var controls = document.getElementById('controls').children.children;

or

var controls = document.getElementById('controls').children;
var controls = controls.children;

Upvotes: 1

Views: 4110

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

Use document.querySelectorAll()

var controls = document.querySelectorAll('#controls > div');
console.log(controls)

Supports IE8+


Here controls is an array, so you need to iterate them to change its properties

button1.onclick = function () {
    var controls = document.querySelectorAll('#controls > div');
    for (var i = 0; i < controls.length; i++) {
        controls[i].className = controls[i].className.replace(new RegExp('\b' + active + '\b'), '');
    }
    this.className += ' active';
};

Upvotes: 2

Related Questions