I have the following code snippet:
$("#mudarcss").click(function(){
$(".teste").css("background-color", "blue");
});
$("#adicionardiv").click(function(){
$("#conteudo").append("<div class='teste'>Minha Div 2</div>");
});
.teste {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="conteudo">
<div class="teste">Minha Div 1</div>
</div>
<br />
<button id="mudarcss">Mudar css</button>
<button id="adicionardiv">Adicionar Div 2</button>
Note that in the result generated by the above code, a div
with red background is created. After clicking the Change css button the div
will have the blue background. Until then everything is working out as expected, but clicking the Add Div 2 button, then a new div
is added with the red background.
I understand that the new div
does not exist yet when the background of the first has changed, and it seems that JavaScript only changes the attributes of the elements that already existed at that time in the DOM context, and does not change the attributes CSS (which are within the <style>
tags) present on the page.
Is there any way to make the style definitely changed to existing elements and to those that will exist via JavaScript, or do I have to resort to another alternative?