I have always disliked using ids and classes as selectors for obvious reasons: ids are unique and classes have to do with styles and should be able to change without affecting functionality of the site.
I used to create things like
<div rel="foo">...</div>
$("[rel=foo]").click(..);
What is the proper way to do this with HTML5? I was tempted by role, but it appears, this attribute has a specific meaning and purpose.
I am just learning HTML5 and your help is greatly appreciated!
You can add any number of classes to your element. And when you selecting, you can use one class as selector.
<div class="class1 class2 foo">
selector,
$(".foo").click(..);
you don't need to defined foo class inside your CSS
Try not using rel, choose title instead. Then you can use jQuery like this:
$('div[title="foo"]').click(...);
Using title, id or class is proper for HTML5. Also, I think you should revisit using classes and IDs as selectors - it's very handy, efficient and easy.
Don't go against the wildly accepted solution here: use the class attribute.
Try to elaborate a naming convention that maps the structure of your pages and components in these pages.
Related
Let's say I have on page 2000 elements. I want to inject into this page elements (banners) from custom module. This module's css file has 300+ css selectors, each selector needs to have unique dynamic prefix to avoid conflicts with other modules inside the same page. I can not use 1 unique id selector because more banners can be loaded, so I need to use something like this:
<div id="company_banner14"></div>
<div id="company_banner15"></div>
div[id^='company_banner']{
}
or
<div id="company_banner14" class="company_banner"></div>
<div id="company_banner15" class="company_banner"></div>
.company_banner{
}
What is better from performance view? Is using regex selector bad practice, would 300 regex selectors make any visible performance impact?
After looking at what you need is have a custom CSS for all elements. There are some points that should be kept in mind for this query.
Using Inline CSS- I think inline CSS is the best solution if you are not using long CSS for one element. It saves very valuable amount of code to your page if your loop too many elements. For example, <div id="company_banner15" class="company_banner" style="Width:x; height:y;"></div>
Using CSS Classes- It is the alternate way for Inline CSS but not as code saver as Inline CSS. if your using same type of style to all elements it is accurate not not if your using different type of style in loop.
Hope these suggestion will guide you. Thanks and cheers.
I have a table where I show/hide a full column by jQuery via a CSS class that doesn't exist:
<table>
<thead>
<tr>
<th></th>
<th class="target"></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td class="target"></td>
<td></td>
</tr>
<tr>
<td></td>
<td class="target"></td>
<td></td>
</tr>
</tbody>
</table>
With this DOM I can do this in one line via jQuery: $('.target').css('display','none');
This works perfectly, but is it valid to use CSS classes that aren't defined? Should I create an empty class for it?
<style>.target{}</style>
Are there any side effects or is there a better way to do this?
"CSS class" is a misnomer; class is an attribute (or a property, in terms of scripting) that you assign to HTML elements. In other words, you declare classes in HTML, not CSS, so in your case the "target" class does in fact exist on those specific elements, and your markup is perfectly valid as it is.
This doesn't necessarily mean that you need to have a class declared in the HTML before you can use it in CSS either. See ruakh's comment. Whether or not a selector is valid depends entirely on the selector syntax, and CSS has its own set of rules for handling parsing errors, none of which concern the markup at all. Essentially, this means HTML and CSS are completely independent of each other in the validity aspect.1
Once you understand that, it becomes clear that there is no side effect of not defining a .target rule in your stylesheet.2 When you assign classes to your elements, you can reference those elements by those classes either in a stylesheet, or a script, or both. Neither has a dependency on the other. Instead, they both refer to the markup (or, more precisely, its DOM representation). This principle applies even if you're using JavaScript to apply styles, as you're doing in your jQuery one-liner.
When you write a CSS rule with a class selector, all you're saying is "I want to apply styles to elements that belong to this class." Similarly, when you write a script to retrieve elements by a certain class name, you're saying "I want to do things with elements that belong to this class." Whether or not there are elements that belong to the class in question is a separate issue altogether.
1 This is also why a CSS ID selector matches all elements with the given ID regardless of whether the ID appears exactly once, or multiple times (resulting in a non-conforming HTML document).
2 The only situation I'm aware of where an empty CSS rule like that is necessary is when some browsers refuse to apply certain other rules properly as the result of a bug; creating an empty rule will cause those other rules to be applied for some reason. See this answer for an example of such a bug. However this is on the CSS side and therefore should have nothing to do with the markup.
There are no ill effects to use classes which don't have styles. Indeed, that's part of the usefulness of CSS is that it's de-coupled from the markup and can style or not style elements/classes/etc. as needed.
Don't think of them as "CSS classes." Think of them as "classes" which CSS happens to also use if it needs to.
According to HTML5 specification:
A class attribute must have a value that is a set of space-separated
tokens representing the various classes that the element belongs to.
... There are no additional restrictions on the tokens authors can use in
the class attribute, but authors are encouraged to use values that
describe the nature of the content, rather than values that describe
the desired presentation of the content.
Also, in the version 4:
The class attribute has several roles in HTML:
As a style sheet selector (when an author wishes to assign style
information to a set of elements).
For general purpose processing by
user agents.
Your use case falls under the second scenario, which makes it a legitimate example of using a class attribute.
You can use a class which has no styles, this is entirely valid HTML.
A class referenced in a CSS file is not a definition of a class, it is used as a selector rule for styling purposes.
When you use a classname in JavaScript, it does not look at the CSS to find that class. It looks directly in the HTML code.
All that is required is that the classname is in the HTML. It does not need to be in the CSS.
In fact, many people think it's actually a good idea to keep separate classes use with CSS and Javascript, as it allows your designers and coders to work independently without getting in each other's way by using each other's classes.
(note, the above paragraph is obviously more applicable for larger projects, so don't feel that you have to go to this extreme if you're working on your own; I mentioned it to make the point that the two can be entirely separate)
You can use CSS classes without using it, but I suggest that if you are adding CSS classes just for the JavaScript/jQuery code, prefix with it js-YourClassName so the front-end developers never use these classes to style the elements. They should understand that these classes can be removed at any time.
The moment you add the Class in your HTML the Class will be defined, so your solution is completely fine
It's not necessary to define CSS classes in your stylesheet. It should work just fine. However, adding it won't harm.
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.
As is mentioned by so many others, yes, using classes with no assigned CSS is perfectly valid and rather than thinking of them as 'CSS classes' you should simply recognise the semantics of class and ID to be groups and individual elements respectively.
I wanted to chip in as I felt an important point hasn't been raised given the example. If you ever need to do visual manipulations to a variable length of elements (in this case you're using table rows) then it always makes sense to recognise that the cost of doing so through Javascript could potentially be very expensive (e.g if you have thousands of rows).
In this situation let's say we know that column 2 always has the potential to be hidden (it's a conscious function of your table) then it makes sense to design a CSS style to handle this use case.
table.target-hidden .target { display: none; }
Then rather than using JS to traverse through the DOM finding N elements we simply need to toggle a class on one (our table).
$("table").addClass("target-hidden")
By assigning the table an ID this would be even quicker and you could even just refer to the column by using the :nth-child selector which would reduce your markup further but I can't comment on efficiency. Another reason for doing this is that I hate inline styling, and will go to great lengths to eradicate it!
It will have no effect if you apply a class on a HTML element, and that class is not defined in CSS. It is a common practice and like Aamir afridi said if you are using classes for js only purpose, it is a good practice to prefix them with js- .
It is not only valid for calsses, but also for id attribute of html elements.
There's no problem at all of using classes to just query for elements. I used to give such class names the sys- prefix (for example, I'll name your class sys-target) to distinguish them from classes used for styling. This was a convention used by some microsoft developers in the past. I also noticed a growing practice of using the js- prefix for this purpose.
If you are not comfortable with using classes for purposes other than styling, I recommend using the Role.js jQuery plugin which allows you to achieve the same purpose using the role attribute, so, you may write your markup as <td role="target"> and query for it using $("#target"). The project page has good description and examples. I use this plugin for big projects because I really like keeping classes for styling purposes only.
Refer to the jQuery validation engine. Even in there we also use non-existent classes to add validation rules on the HTML attributes. So there is nothing wrong in using classes that are not actually declared in a stylesheet.
I've been applying an ID to the body tag of my HTML documents lately to allow greater CSS control (#9). Recently the though occurred to me that I could do exactly the same thing by applying a class to the body tag. I want to know positives and negatives of each choice. If I have multiple pages where the body tag has the same ID, is it better to use a class? What do you think? Why?
UPDATE: The class/ID is basically what I intend to use to identify to the stylesheet which page or type of page the stylesheet is being applied to. For example, is it the homepage, the contact page, one of many search results pages, an archive page, etc?
Using a class is perfectly acceptable, possibly more so than using an id. Use of ids should be limited as much as possible, because they can clash with other ids and break things like document.getElementById.
An id selector is more specific than a class selector, which usually makes it a better choice for your use case.
-- David Dorward
However, a high "specificness" is not always desirable. Consider body#faq #col_b a {color:gray;} in master stylesheet and then someone develops a plugin with a gray background that goes on faq page, now they need to use !important or create another id attribute to give higher specificity.
Also, consider the use of multiple classes in a single body element:
<body class="faq two_column big_footer"> ...
An id selector is more specific than a class selector, which usually makes it a better choice for your use case.
ID needs to be unique per page (if you want valid markup), meaning only one instance of a particular ID should exist on a page.
Classes, on the other hand, can be applied to numerous elements per page. Use classes for things that reuse the same styles and use IDs for more unique elements that require their own styling.
Ideally, use classes whenever possible and limit the use of IDs.
For more information on ID, see here, and more on classes, see here.
It is better to use a class if you plan to reuse a style in pages. IDs are good if style sheet is designed for a specific page. But still depends on your app.
You can (read: should) only use the id on the body tag.
ID = single use per page
Class = multiple uses
1 Body tag = 1 id tag. This can be the same on different pages. Essentially, using the class tag is probably overkill for this purpose.
In HTML5, the id attribute can be used on any HTML element (it will validate on any HTML element. However, it is not necessarily useful).
In HTML 4.01, the id attribute cannot be used with: <base>, <head>, <html>, <meta>, <param>, <script>, <style>, and <title>.
Note: HTML 4.01 has greater restrictions on the content of id values (for example; in HTML 4.01 id values cannot start with a number).
Source: W3School
I can imagine it can get complicated fast trying to debug style issues when there are multiple classes associated with elements. Currently I'm using multiple classes but in a way that one type of class is for jQuery manipulation and the other is for style. So I can have an element
<div id='myDiv' class'ActionControl SearchBox'></div>
where the .ActionControl is used by jQuery and the .SearchBox has a style associated in the CSS file. Is this right or wrong? What do people more experienced with this think?
What issues have other people come up against? How have they been resolved?
As long as your code is comprehensible, maintainable and clear to others, your system is good.
There is no standard I am aware of in how to give CSS classes, except one:
If you need to target a single element in the page using JS or CSS you should use an ID and not CLASS.
This is definitely a good practice...
What you have to keep in mind always is not to remove the class attribute, instead you will be removing the classes you exactly want to remove.
Also, another problem (not for me) is that multiple classes are not supported for OLDER browsers.
Keep in mind to code your CSS in a way it prevent code duplication so a float:left class can be used in many different elements, this is to keep code clear.
I can't see anything wrong with that. Probably, you could prefix the jQuery classes with e.g. jActionControl, so you have a better overview over who uses what classe if it gets really ugly with many classes.
Of course, you can assign as many classes as you want so there is nothing wrong with your approach in my eyes.
Another way to use multiple classes is to get a kind of inheritance.
.thing { ..blah.. }
.thing.subthing { ..tweaks.. }
<div class="thing"></div>
<div class="thing"></div>
<div class="thing subthing"></div>
Here all the things get "blah" applied to them, but only the subthing div gets the tweaks.
Yes, it can get complicated. As with any power tool, you need to apply it judiciously and with discipline.
Ive been wondering... in CSS are there any differences between creating a style class and applying it an element, or creating a style with the #elementId notation (apart from being able to assign a class to different elements)?
For example...
#div1
{
background-color: Yellow;
}
<div id="div1">
Hello world!
</div>
Or
.div1
{
background-color: Yellow;
}
<div class="div1">
Hello world!
</div>
Thanks! :)
An ID must be unique in a document. Classes can be used in any number and combination. So you can use one class on multiple elements and multiple classes on one element.
One other difference; id-selectors are more specific than class-selectors, so I believe they will "trump" any other selector that exists. You can use "important" to do the same thing, but and id selector may be easier.
But id-selectors should be used sparingly...
Many classes can include a given "class" while only one element may be identified by a given ID. If you need to locate an unique Element use ID, otherwise if you wish to mark many elements that are basically the same but in different spots in your html use 'class'.
You sort of answered your own question, they are just mechanisms to 'identify' elements.
using #elementID applies only to the element uniquely identified by that id. a class can be used by multiple elements
there is however an order of precedence. selectors using the id have greater weight than selectors using class and when there is a collision the #id selector will take precedence
edit: see http://kiribao.blogspot.com/2008/03/css-selectors-precedence-and-ways-to.html for more detail on selector precedence
edit: also see the w3c specs at http://www.w3.org/TR/CSS21/cascade.html#specificity
Performance or functionality-wise, there is no difference [citation needed].
The only real difference is semantic, if you are working on a single node with a unique ID, or if you need a reusable class marking several nodes.
There are some differences:
Uniqueness
IDs must be unique, classes can be repeated. This is logical if you look at their expected usage.
Usage
IDs should be used to denote large sections of a website (e.g. #header), or unique elements that are accessed via Javascript (e.g. #killSession)
Classes should be used for reusable parts.
Specifity
IDs get assigned a specifity value of 100, while classes are only worth 1.
So this rule:
#id .class
Is worth 101 points.
This rule:
#id #id2
Is worth 200 points and will always trump the #id .class rule (regardless of the source order).
Performance
Performance wise, getting elements by ID is always faster than class, especially when talking Javascript. I'd love to see someone add some cold hard numbers to this.
Discussion
An interesting discussion about the performance of selectors can be found at Shaun Inman's blog.
The usage of classes is debated in Jeff Croft Applying OOP concepts to CSS
Classes are to group together elements which share similar functionality (for scripting) and/or layout (for styling). IDs should always be unique identifiers for elements.
A good example for something which should have an ID is the content area of your document, which is common to use the #content ID for. Classes are good for anything else which may occur twice in your document, such as headers which should have special markup or behavior, or links which should open a lightbox instead of the normal "go to URL" behavior.
HTH.