0
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>
<div id="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
bottom-up red is created. After clicking the button Change css to div
now has the bottom blue. Until then everything is going as imagined, but when you click the button Add Div 2, then a new div
is added with the background red.
I understand the new div
did not exist yet when the background of the first was changed, and it seems that Javascript only changes the attributes of the elements that already existed at that time in the context of the DOM, and does not change at all the CSS attributes (that are within the tags <style>
) present on the page.
Is there any way to make the style is definitely changed to the existing elements and to those that will exist via Javascript, or I will have to resort to another alternative?
Instead of changing the CSS, isn’t it easier to create both styles and the button to change the state of a variable that tells you what the current style is? Changing CSS by JS is not something cool in this case, just change the
className
of the element and the new ones already create the newclassName
– Gabriel Katakura
Boa @Gabrielkatakura ... Makes a lot more sense! rsrsrs...
– Jedaias Rodrigues