When dynamically adding an element to a parent div, I encounter an issue where the styles defined in my CSS are not applied to the newly added element.
$('.some_div').append("<li class='hi'>hey!</li>")
Although I can manually add the styles using JavaScript like this:
$('.some_div').append("<li class='hi'>hey!</li>")
$('li.hi').css({"color":"white"});
I find this redundant as the style is already defined in my CSS file. Is there a way to avoid this redundancy?
Update:
$('.some_div').append('<li style="color:white" >hey!</li>')
This solution works but still feels redundant since the style is defined elsewhere in the CSS file. Is there a way to apply the existing styles without having to re-define them in a css()
function?
In my CSS file,
.some_div > li {
font-size: 20px;
background-color: 30px;
margin-right: 2px;
}
.hi {
color: white;
}
It seems that none of these styles get applied when using ($).append()
, leading me to wonder if there is a better way to handle applying pre-defined styles.