Is there a way to apply CSS styling using jQuery?
When using jQuery's css
function, it does not create CSS rules. Instead, the function looks for elements that match the selector provided in the DOM at the time of calling the function. It then sets the inline style of each matched element accordingly.
If you find that nothing happens when running the code, it may be because at that particular moment, no elements matched the selector or any changes made were not visually noticeable.
To add a CSS rule that applies to existing elements and future ones as well, you can append a style
element like this:
$("head").append(
$("<style/>").text(
".switch-vertical input ~ input:checked ~ .toggle-outside .toggle-inside {\n" +
" top: 40px;\n" +
"}\"
)
);
Check out the live example below:
setTimeout(() => {
$("head").append(
$("<style/>").text(
".switch-vertical input ~ input:checked ~ .toggle-outside .toggle-inside {\n" +
" top: 40px;\n" +
"}"
)
);
}, 800);
<div class="switch-vertical">
<input />
<input type="checkbox" checked />
<div class="toggle-outside">
<div class="toggle-inside" style="position: relative">
Lorem ipsum
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
(Please note: The HTML used above is from Rory McCrossan's answer, with the addition of position: relative
to demonstrate movement when applying the CSS.)
Even after trying this method, nothing seems to happen without any error messages. Why is that?
Indeed, jQuery operates based on sets. Performing actions on an empty set does not result in an error; it simply means that no changes will occur. 😊