One thing that nobody here has fully mentioned is that JavaScript (aided by jQuery in this case) isn't able to directly modify a document's cascading style sheet. jQuery's css()
method merely changes the matched set of elements' style
property. CSS and JavaScript are completely unrelated in this aspect.
$('.target').css('display','none');
doesn't change your .target { }
CSS declaration at all. What has happened here instead is that any element with a class
of "target" now looks something like this:
<element class="target" style="display:none;"></element>
Are there any side effects caused by not pre-defining a CSS style rule? None whatsoever.
Is there a better way to do this? Performance-wise, yes there is!
How can the performance be improved?
Rather than directly modifying the style
of each element, instead you can pre-define a new class and add that to your matched elements using addClass()
(another jQuery method).
Based on this pre-existing JSPerf which compares css()
with addClass()
, we can see that addClass()
is actually much faster:
How can we implement this ourselves?
Firstly we can add in our new CSS declaration:
.hidden {
display: none;
}
Your HTML would remain the same, this pre-defined class is simply in place for later use.
We can now modify the JavaScript to use addClass()
instead:
$('.target').addClass('hidden');
When running this code, rather than directly modifying the style
property of each of your matched "target" elements, this new class will now have been added:
<element class="target hidden"></element>
With the new "hidden" class, this element will inherit the styling declared in your CSS and your element will be set to no longer display.
.css
, styles set with .css are very difficult to override without causing other issues so i tend to avoid them. – Participial.toggle()
, its a tiny bit shorter in your code. – Anchylosetarget
is for javascript's purposes, a lot of people use the prefixjs-
for such classes, i.e.js-target
. BTW: Target is kind of a bad name ;) For further reading see: philipwalton.com/articles/decoupling-html-css-and-javascript – Forsythe$('.target').hide()
– Overshine