简体   繁体   中英

CSS Parent Element

I want to dynamically apply CSS style based on parent css property of a div element. Is there a way in javascript to do this/ is this possible? Example of code :

<div clas="parent">
     <div class="child">
          <div class="x"></div>
     </div>
</div>

Based on parent class css property, i want to toggle css property for class x

Do you really need to use JavaScript to toggle something based on a parent class. You can just do it in pure CSS.

.parent .child .x {
     background-color: red; /* default */
}


.parent.someClass .child .x {
     background-color: yellow; /* overrides the default with specificity */
}
var y = document.getElementById('child').parentNode.className;
if (y=="active") {
document.getElementById('x').style.background = '#ff0000';
}

Demo: http://codepen.io/simsketch/pen/vgNjdp

Hope this helps!

First, you grab element using querySelector , then you can change class using className .

In your example, to change color to red you could do:

document.querySelector('.parent .child div').className = "x"

To toggle class you could use classList.toggle("x")

document.querySelector('.parent .child div').classList.toggle("x")`

If you have access to jQuery , you can acheive it with very specific selectors like so:

 $('.x').each(function() { if ($(this).closest($('.parent')).hasClass('makeBlue')) { $(this).addClass('turnBlue'); } if ($(this).closest($('.parent')).hasClass('makeRed')) { $(this).addClass('turnRed'); } }); 
 .x.turnBlue { background-color: blue; width: 250px; height: 250px; } .x.turnRed { background-color: red; width: 250px; height: 250px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <div class="parent makeBlue"> <div class="child"> <div class="x"></div> </div> </div> <div class="parent makeRed"> <div class="child"> <div class="x"></div> </div> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM