Reputation: 41
I have got a preview box that gets the color and then changes it when the user does. However i have a child div that needs changine. how can i select the child div through get element by id? this is the java script i have at the moment, how do i change this so i can get the child div front to change color
document.getElementById("flip3D").style.backgroundColor=p1;
#flip3D{
width:200px;
height:200px;
margin:20px;
float:left;
}
#flip3D > .front{
... style stuff is all there just to much toput in and worry about
}
Upvotes: 0
Views: 63
Reputation: 844
The simpleste way to do this is by using CSS. Change the background-color to inherit, that way they will allways have the color of their parent.
.child-node {
background-color: inherit;
}
Upvotes: 0
Reputation: 7
My first suggestion would be to use jQuery for this type of manipulation. It makes navigating the DOM and changing attributes much easier.
My second suggestion would be to control the color of both elements with a class. So your CSS might look something like this:
#flip3D{
width:200px;
height:200px;
margin:20px;
float:left;
background: /*whatever you want the initial color to be*/;
}
#flip3D > .front {
/*Initial styling*/
}
#flip3D.stateChanged{
background: /*Whatever you want the new color to be*/;
}
#flip3D.stateChanged > .front {
/*New styling*/
}
Then in your Javascript you would change the class like this:
jQuery Example (using toggleClass):
jQuery('#flip3D').toggleClass('stateChanged');
You can also do the class manipulation in vanilla javascript but it is much messier. Something like this:
var ele = document.getElementById('#flip3D');
if(ele.className == 'stateChanged')
ele.className = '';
else
ele.className = 'stateChanged';
Upvotes: 0
Reputation: 206618
You mean something like this?
var front = document.querySelectorAll('#flip3D .front');
for(var i=0; i<front.length; i++){
front[i].style.backgroundColor = 'red';
}
or like:
var flipEl = document.getElementById("flip3D");
var frontEl = flipEl.getElementsByClassName('front');
for(var i=0; i<frontEl.length; i++){
frontEl[i].style.backgroundColor = p1;
}
Why not do it using CSS? (Your Question is pretty unclear so my hands are tied)
Upvotes: 1
Reputation: 19802
You could go with .childNodes()
and .children()
(Google will give you a lot of learning resources for these two methods. )
They will aid in selecting child elements within the DOM, of a specific element.
Upvotes: 0