Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select all children of an element with javascript and change CSS property?

Tags:

I am working on a project that has a div with 32 children. I need to create a dropdown menu that will change the background of each div and the parent. For the other parts of the project that don't have children, I have been using the following code:

function changediv(color) { document.getElementById('div1').style.background = color; } 

HTML:

<select> <option onClick="changediv('#555');">Hex</option> <option onClick="changediv('blue');">Colorname</option> <option onClick="changediv('url(example.com/example.png)');">Image</option> </select> 

I could just add a different ID to each child (id1,id2,id3,...), but there are 32 children and not only would I have to add 32 IDs, but also 32 lines of Javascript. There has to be a better way; somehow selecting children or even changing the actual CSS code that selects the children.

Thanks, Ian

like image 923
Ian Avatar asked Mar 20 '12 01:03

Ian


People also ask

Can we change CSS properties values using JavaScript?

CSS variables have access to the DOM, which means that you can change them with JavaScript.

How do I select all child elements except one in CSS?

How to select all children of an element except the last child using CSS? When designing and developing web applications, sometimes we need to select all the child elements of an element except the last element. To select all the children of an element except the last child, use :not and :last-child pseudo classes.

How do I select all children in a div?

The span “display” is “block”. Then, we have the “div. child > *” selector which selects all the elements of the div class named “child” using the “*”. The “*” selects all the child elements.


2 Answers

While this can be done in one line with JQuery, I am assuming you are not using JQuery - in which case, your code will be:

var nodes = document.getElementById('ID_of_parent').childNodes; for(var i=0; i<nodes.length; i++) {     if (nodes[i].nodeName.toLowerCase() == 'div') {          nodes[i].style.background = color;      } } 

See http://jsfiddle.net/SxPxN/ for a quick example I created - Click on "change 'em" to see it in action

like image 140
Vijay Agrawal Avatar answered Sep 21 '22 13:09

Vijay Agrawal


Try to use below codes:

var nodes = document.getElementById('ID_of_parent').getElementsByTagName("div"); for(var i=0; i<nodes.length; i++) {     nodes[i].style.background = color; } 
like image 30
Evan Hu Avatar answered Sep 20 '22 13:09

Evan Hu