0

This may be a stupid question, maybe I have been up too long, but is there any way to add a class to an element and have it affect the elements children only?

$('#add').click(function(){ $('.parent').append("<div class='child'></div>"); }); $('#bg').click(function(){ $('.child').css('background-color', 'orange'); });
.parent { background-color:yellow; border: 2px solid black; height:200px; width: 300px; } .child { height:15px; width:280px; border: 1px solid black; margin-top:10px; margin-bottom:10px; margin-left:5px; background-color:white; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class='parent'> <button id='add'>Add another</button><button id='bg'>Change Background</button> <div class='child'></div> <div class='child'></div> <div class='child'></div> </div>

Refer to snippet, I need the parent div background color to remain white, but I need to change the css so it affects all future dynamically created div's.

1
  • Yes, but without specifically creating the div dynamically with the class in the append function concatenation, it wont apply Commented Aug 5, 2015 at 19:38

2 Answers 2

2

Add a class to the .parent div and have it affect the children:

$('#add').click(function() { $('.parent').append("<div class='child'></div>"); }); $('#bg').click(function() { $('.parent').addClass('orange-bg'); });
.child { height: 15px; width: 280px; border: 1px solid black; margin-top: 10px; margin-bottom: 10px; margin-left: 5px; background-color: white; } .parent { background-color: yellow; border: 2px solid black; height: 200px; width: 300px; } .parent.orange-bg .child { background-color: orange }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class='parent'> <button id='add'>Add another</button> <button id='bg'>Change Background</button> <div class='child'></div> <div class='child'></div> <div class='child'></div> </div>

Sign up to request clarification or add additional context in comments.

1 Comment

the .parent.orange-bg .child syntax is exactly what i was looking for. My program is more complex than the example I gave, and I have tonnes of classes and ids, so I am having a hard time wrapping my head around it all. Thanks
1

use the css as follows

.parent .child { // your css here } 

This css will be applied to all the elements which have a parent with class parent.

1 Comment

The OP doesn't want to affect all children initially, only after the background has been changed. The OP said "all future dynamically created div's"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.