1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Using id or class

Discussion in 'CSS' started by gandalf117, Mar 22, 2013.

  1. #1
    This may be a beginners question but I am not completely sure about this.

    Usually the classes are used when you want to apply the same style to more than one division, link, element, etc. But what if you have a division for which you want a unique style are you obliged to use an id. Can you still use a class as a way to select it in that case? Does it matter?

    The same dilemma exists when it comes to jQuery. Do you use $(".someName").click();
    or do you use $("#someName").click();

    Again I am talking about applying styling and functions to a single element. I am not sure whether even in those cases classes aren't better to use than ids, because one can always change their mind and decide to include another element with the same styling and then the selector has to be changed from id to class. Do you see what I mean? What is the good practice here?
     
    gandalf117, Mar 22, 2013 IP
  2. Logist

    Logist Greenhorn

    Messages:
    20
    Likes Received:
    0
    Best Answers:
    1
    Trophy Points:
    21
    #2
    The simple difference between the two is that while a class can be used repeatedly on a page, an ID must only be used once per page. Therefore, it is appropriate to use an ID on the div element that is marking up the main content on the page, as there will only be one main content section. An ID makes it much easy and efficient to find a particular element in Javascript.
     
    Logist, Mar 22, 2013 IP
  3. gandalf117

    gandalf117 Active Member

    Messages:
    111
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    53
    #3

    What if you have not one or two but many div elements that require individual styling?
     
    gandalf117, Mar 23, 2013 IP
  4. wiicker95

    wiicker95 Well-Known Member

    Messages:
    438
    Likes Received:
    37
    Best Answers:
    10
    Trophy Points:
    100
    #4
    At first glance, this question may seem a bit hard to answer correctly, but in fact it isn't. You actually answer to your own question, that's the thing. One thing though. When you establish a well-structured semantic markup, the classes are not even needed in 80% of cases.

    For markable containers, main page wrappers, you use ID, since they're unique, and that ID value usually corresponds to their meaning and role in your markup.
    If the same containers/boxes are repeated, and they all have the same or no semantic meaning, then you use classes.

    Let's say you want to create and style a navbar. That's UL's job ok. Since there's only one navbar on your website, it'll be an ID, and its value will describe that particular element, like <ul id="navigation"> or whatever.
    The UL's children, LI elements, along with their own children, anchors, won't need any class, since you can use the parent/child CSS nesting relation, with #navigation li, or #navigation li a. Any class declaration would be pointlessly redundant here.

    Now say you have a main content part, and an extra thumbnail part aside, usually called sidebar. Since you can't associate these to any semantically meaningful element in HTML, you'll use DIV, with ID for both (#main and #sidebar, for instance). Inside each of them, you have another set of nested containers, which cannot be associated to any semantically meaningful element in HTML. Again, you will use DIV.
    We will admit that they are ALL styled the same way. Writing #main div or #sidebar div is pointlessly ambiguous, since it may not be the only div in that container, you will therefore give them classes.

    Once you grasp this nesting logic, you'll be able to determine easily whether an element has an ID, class, or neither ID nor class. I should also mention that class stacking is bad practice, if you must declare multiple classes for one element, then you're doing something wrong. Combining both may be useful, but it's by no means mandatory or cooler than just one of them, or even none.

    --edit--

    I didn't see the jQuery part before. The answer is, when it comes to jQuery, don't go anywhere near jQuery.
     
    Last edited: Mar 23, 2013
    wiicker95, Mar 23, 2013 IP
    GMF and kk5st like this.
  5. Logist

    Logist Greenhorn

    Messages:
    20
    Likes Received:
    0
    Best Answers:
    1
    Trophy Points:
    21
    #5
    Use selector effectively, try to use an ID instead of passing a class.
    You can use Firebug and Console for testing you script and you will see a difference.
    console.profile() ;
    $("#someName").click();
    console.profileEnd();
    Code (markup):
     
    Logist, Mar 23, 2013 IP
  6. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #6
    Classes are used for the application of style, it is their only reason to exist -- if ALL you are doing is applying style, be it to one element or many, use a class. Using classes as a means of selecting tags is a kludge, and not something javascript was ever really meant to do at the start or by design. Selecting by className is slow, painful, even when the new scripting provides support for it compared to targeting by ID. If it's unique, and you're targeting it directly, that's ID's job.

    ... and you have to look at what ID's "job" actually is -- and that being:

    1) to target it as a single element from scripting in a reasonably fast manner.
    2) as a target for attributes like FOR (label) and HEADERS (td/th)
    3) target from a hash in a URL instead of the old idiotic <a name="something"></a> garbage.

    The last of these it's a bit surprising how many people don't know this works... old school if you had something like this:

    <a href="#content">Skip to content</a>

    to create #content you would have created an extra empty anchor for no good reason except as a landing pad for the hash.
    <a name="content"></a>

    But if you have a DIV with the ID of content
    <div id="content">

    That will work as a target too.

    Classes are for styling, ID's are for targeting... that you can style off ID is more a happy extra they threw in for good measure.
     
    deathshadow, Mar 24, 2013 IP
  7. wiicker95

    wiicker95 Well-Known Member

    Messages:
    438
    Likes Received:
    37
    Best Answers:
    10
    Trophy Points:
    100
    #7
    @DS, what you say about ID targeting is true, but since they did what they did, and that is "threw a happy extra in", there's no such distinction anymore. Saying that ID are ONLY for targeting, and class ONLY for styling is pretty much false.

    About that <a name="content"></a>, well that's some idiotic garbage you could have seen a long time ago, but they all realized that an anchor without href makes no sense, so they are now spitting even more idiotic stuff, like <a href="javascript:void(0)" onclick="something(); return false;">Click Here</a>. How far people go in misusing the normative conventions is beyond me.
     
    wiicker95, Mar 24, 2013 IP
  8. gandalf117

    gandalf117 Active Member

    Messages:
    111
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    53
    #8

    I really don't understand why are <a name="content"></a>, <a href="#content"></a> or <a href="javascript:void(0)" onclick="something(); return false;"> idiotic garbage?

    Since I started learning web development 10 years ago these things have existed. This is the first time I hear this. What is so wrong with them? And what does this have to do with classes and ids?
     
    gandalf117, Mar 26, 2013 IP
  9. wiicker95

    wiicker95 Well-Known Member

    Messages:
    438
    Likes Received:
    37
    Best Answers:
    10
    Trophy Points:
    100
    #9
    Absolutely nothing is wrong with <a href="#content">.
    <a name="content"> is redundantly useless, and garbage since CSS and targeting with ID (i.e. #).

    BTW, I have also seen this one :

    <a href="javascript:void(0)" onclick="location.href='http://www.xxx.com'"> (that's an example, don't visit that website)

    It's about ID targeting ds mentioned. Read his post.
     
    wiicker95, Mar 26, 2013 IP
  10. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #10
    ID is shorter, can be applied to an existing element speeding up DOM access by having one less element on the DOM [i(which is also ANOTHER reason I consider HTML 5's new structural tags to be pointless BS).[/i]

    Only thing that's garbage about that is a complete lack of CONTENT for the anchor... nothing wrong with href="#content" though.


    If you're not going to have an anchor do what an anchor does (go to hrefs) why use an anchor instead of a SPAN, DIV or possibly even some already existing parent tag? "onclick" exists on every element, not just anchors... You also wouldn't have to return false since clicking on most non-anchor tags doesn't do anything unless there's a parent anchor involved.

    Though really, IMHO good scripting should be self attaching, and not inlined in the markup with an attribute.

    ... most of them have been in 'common practice' despite being wrong, or outdated, or just plain pointless bloat; doesn't make it right any more than pissing out a PSD and calling yourself a 'designer', still using embed, or the common practice of still sleazing out HMTL 3.2 and slapping either 4 tranny on it or 5's lip-service around it.

    ID's are part of targeting with a hash:

    <a href="#content">Skip to Content</a>
    <p>
      non "content" stuff here
    </p>
    <div id="content">
      <p>
        content here
      </p>
    <!-- #content --></div>
    Code (markup):
    WORKS. the ID replaces <a name="content"></a>, no longer needed as of... IE 5.5 I think so some 14 years?

    ID's are part of targeting with FOR
    <label for="contactName">Name:</label>
    <input type="text" name="name" id="contactName" />
    Code (markup):
    Has the nice side effect that if you click on the label, it selects the input -- REALLY handy with checkboxes/radiobuttons.

    ID's are for targeting single elements with JS
    target=document.getElementByID('target');
    Code (markup):
    Remember, 'getElementsByClassName' is a NEW concept... originally you weren't even supposed to try and do that as that's not what classes were FOR. Classes were only created to apply style, and that's IT. Developers just want them to do more since ID's are unique. (though honestly most cases people use getElementsByClassName they should be walking the DOM off a parent element's ID or getting by TagName)

    It was one of the examples of what ID's exist FOR.
     
    deathshadow, Mar 26, 2013 IP
  11. TestingWhiz1

    TestingWhiz1 Member

    Messages:
    64
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    28
    #11
    The id selector is used to specify a style for a single, unique element.The class selector is used to specify a style for a group of elements.In simple terms, if a class selector and ID selector were to be in conflict, the ID selector would be chosen.
     
    TestingWhiz1, Mar 28, 2013 IP
  12. gandalf117

    gandalf117 Active Member

    Messages:
    111
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    53
    #12
    I don't entirely understand the meaning of this sentence, especially the tranny part, lol


    The rest I think I understood.

    deathshawod and wiiker95 I really appreciate the input. From this tread I learnt:
    - that in most cases using IDs is a better practice than classes, especially when it comes to javascript
    - the browser works faster with IDs than with classes
    - with anchors it is better to use the href attribute instead of the name, onclick or other attributes
     
    gandalf117, Mar 31, 2013 IP
  13. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #13
    Lemme break it down...

    1) "pissing out a PSD" -- starting out drawing pretty pictures in Photoshop before you have semantic markup or a working CSS layout applied to that markup is a back-assward way of building a website. While it has become accepted practice, the result is usually (ok, pretty much always) an accessibility disaster.

    2) the EMBED tag was not adopted into 4 strict for being redundant to OBJECT. Since OBJECT can do what EMBED does, EVEN in IE, the only reason to continue using it is the ineptitude of certain developers... Which of course is why for some screwed up reason it was accepted into HTML 5 -- which is just more proof in my mind that HTML 5 is little more than the worst of 1997 coding practices.

    3) "HTML 3.2 with 4 tranny or 5 lip service" -- Most people writing websites so far as I'm concerned are still writing 1997 style HTML 3.2 -- when I say "4 tranny" I'm referring to "HTML 4 Transitional" -- the "transitional" part means that it's in "transition" from 1997 to 1998 coding practices... meaning there are tags and attributes present in the markup that really have no business in there on any new site written after 1998! From studying, experimenting, and building test pages with HTML 5, I've come to the conclusion that HTML 5 does NOT exist for the people who used the real HTML 4 -- aka HTML 4 STRICT -- at all. It seems carefully crafted to justify the sloppy coding practices and encourage a return to the WORST of the HTML 3.2 era browser wars of the mid to late 1990's. The people who used to just sleaze out decade out of date HTML 3.2 methodologies with a HTML 4 transitional doctype on it, now just slap HTML 5's "shortened" doctype and header at the top -- said doctype is so short it's quite literally a 'lip service' just to make older versions of IE not be in 'quirks mode'.

    That passage was pretty much just examples of piss poor practices that are still commonplace... and it often seems with the steaming pile of manure known as HTML 5 they're now being ENCOURAGED... Naturally the lemmings are yumming it right up.
     
    deathshadow, Mar 31, 2013 IP
  14. wiicker95

    wiicker95 Well-Known Member

    Messages:
    438
    Likes Received:
    37
    Best Answers:
    10
    Trophy Points:
    100
    #14
    -We actually said that it depends. Originally, ID were meant for targeting and CLASS for styling, but now it's different. ID are to specify markable containers, target subtile html elements AND style them. CLASS are only meant to style one element or a group of them, under one or multiple different values.

    -No one said that ID are "faster" than CLASS. That statement makes no sense... I'm not sure where you even got that from.

    -Href are most of the time the ONLY anchor attribute. You can optionally specify and ID or CLASS, but under no circumstances a NAME or TITLE.
     
    wiicker95, Mar 31, 2013 IP
  15. gandalf117

    gandalf117 Active Member

    Messages:
    111
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    53
    #15
    aha, now I got your point,

    Here is my position on the three points you mentioned above:
    1) used to do it back in the days when I designed websites. Still don't know a better way than this.
    2) still do it occasionally with videos and flash
    3) I have used HTML 4 transitional a lot in the past. I am not really sure what outdated HTML 3.2 methodologies you mean but it is very likely that I am still using some of them.

    Bottomline is you have some really good points here but in the end of the day is it really that important to always keep up with the new practices and methodologies? Sometimes it is just faster and more comfortable for you to follow the "old ways". I know that this may sound a little ignorant and unprofessional but after all the users of your website are not going to look at your code, right? So what are the real downsides of poor practices?

    BTW do you know any books about good HTML, CSS or even PHP practices? or are these just things that you only learn in the long run and can't find in a book? (obviously I need to update some of my knowledge)
     
    gandalf117, Mar 31, 2013 IP
  16. gandalf117

    gandalf117 Active Member

    Messages:
    111
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    53
    #16
    It is what deathshadow said in his first post:

     
    gandalf117, Mar 31, 2013 IP
  17. wiicker95

    wiicker95 Well-Known Member

    Messages:
    438
    Likes Received:
    37
    Best Answers:
    10
    Trophy Points:
    100
    #17
    No, you didn't understand. He didn't mean that browsers process CLASS faster then ID : he said that targeting elements by class is slow in terms of bytes and time wasted. You need to throw more code at it, hence it being slow. In some cases, some people go with getElementByClass which - doesn't exist! Then they try to tweak it, by adding a letter s in Elements, and/or Name at the end. In the vast majority of cases, they don't even make it, but even if they do, they end up with 10x the code.
     
    wiicker95, Mar 31, 2013 IP
  18. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #18
    Uhm.. NO... TITLE is a core attribute, just like ID and Class it is available to EVERY tag. One of the better reasons to use title on an anchor is for accesskeys.

    If you visit my EWI page in Opera:
    http://www.ewiusb.com/

    ...and hit shift-esc, it will pull up the accesskeys menu (one of the many navigational aids like header navigation most browsers should/would have if they'd get off their asses and finish their HTML 4 implmentations before adding all this HTML 5 BS... of course if they did that, HTML 5 would be even MORE redundant). If you don't put TITLE on the accesskey elements, it will show the href, or in the case of form elements the associated LABEL of the form element (assuming one used FOR properly). If you include TITLE, that is shown instead.

    In most cases though, the point of TITLE is to show information the content of the tag doesn't fully communicate -- which means as a rule of thumb if you 'need' TITLE, there's something wrong with the tag you're applying it to.

    So TITLE on Anchors? Hell yeah... Only a handful of tags should NOT accept the core attributes of ID, CLASS, STYLE and TITLE. The laugh being one of those is the HTML tag itself -- which is another strike against that mess of idiocy Paul Irish came up with of wrapping a bunch of pointless IE conditional comments around the HTML tag that it seems like everyone building HTML 5 sites is adding; Makes that shorter doctype save SO much code...

    Lemme think... HTML, HEAD, BASE, META, SCRIPT, STYLE, TITLE, the deprecated ISINDEX... I think that's all the tags that are NOT supposed to have CLASS, ID, STYLE or TITLE on them. (TITLE on TITLE, yeah that would make sense -- NOT!) AMAZINGLY the W3C Validator fails to report an error on those -- but again the validator even in strict is surprisingly forgiving.

    Title on IMG, well -- that usually makes no sense; redundant to ALT in most cases. It's why the only case I could see a TITLE being warranted for IMG is if it's on an anchor AROUND the IMG. The ALT text describing what the image is, the TITLE on the anchor describing where the link GOES.

    It actually DOES exist in modern browsers as of Firefox 3, Opera 8, and Safari 2 and IE9 (so it's always existed in chrome) -- though it's called getElementsByClassName... Plural because it returns an array of all elements that contain the requested class. "name" added to it since className is the javascript property for pulling up the complete list of associated classes.

    It is slower in SCRIPTING than getElementById. The code to fake getElementsByClassName in legacy versions of IE is even slower, since usually you have to not only pull up a complete list of the entire DOM with getElementsByTagName('*'), you then have to run a regex or indexOf on every single elements' "className" property to find the value you want. (though I've been playing with making my own faster version that just walks the DOM)

    But that ONLY applies to javascript. In terms of CSS any difference between ID and class is not even measurable assuming the DOM isn't ridiculously bloated. (another reason NOT to use all those extra HTML 5 for nothing "structural" tags -- making the DOM bigger for no reason making scripts slower!)

    The "old" methodologies... that are now fifteen years old and appear to be having a revival with HTML 5 basically saying "Go ahead and sleaze it out any old way" are more work, more code, and harder to maintain. The 'newer' methodologies introduced in 1998 (that are still ignored by many) of Semantic markup, separation of presentation from content, logical document structure (well to be fair, that last one was introduced in HTML 2, and then destroyed by HTML 3.2 only to be re-introduced in 4 and again destroyed by 5; it's like grunion or swallows) -- they all combine to speed up development, aid accessibility, make better use of caching models to reduce bandwidth use and speed page loads.

    Right now you have all this noodle doodle bullshit with things like frameworks where people have it in their heads that throwing more code at a page makes things simpler... They often use the frameworks to "save time" or the old methodologies to "Save time" when they end up writing more code with those sleazy crutches than they would WITHOUT THEM! That's 'easier' HOW exactly?!?
     
    deathshadow, Mar 31, 2013 IP
  19. wiicker95

    wiicker95 Well-Known Member

    Messages:
    438
    Likes Received:
    37
    Best Answers:
    10
    Trophy Points:
    100
    #19
    That's pretty much what I say, you didn't read the whole thing I guess.

    I have to give you a full credit for TITLE though, but "core attribute" term is nonsensical in so many ways.
     
    wiicker95, Mar 31, 2013 IP
  20. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #20
    TSDR? re-reading your post I still don't quite come away with that... or at least your wording doesn't make any sense.

    Oh yes, the notion of a set of common attributes found on every tag that can go inside and on BODY is so nonsensical, they couldn't possibly have put it in the DTD alongside "Internationalization attributes" and "event attributes"

    <!ENTITY % coreattrs
     "id          ID             #IMPLIED  -- document-wide unique id --
      class       CDATA          #IMPLIED  -- space-separated list of classes --
      style       %StyleSheet;   #IMPLIED  -- associated style info --
      title       %Text;         #IMPLIED  -- advisory title --"
      >
    
    <!ENTITY % i18n
     "lang        %LanguageCode; #IMPLIED  -- language code --
      dir         (ltr|rtl)      #IMPLIED  -- direction for weak/neutral text --"
      >
    
    <!ENTITY % events
     "onclick     %Script;       #IMPLIED  -- a pointer button was clicked --
      ondblclick  %Script;       #IMPLIED  -- a pointer button was double clicked--
      onmousedown %Script;       #IMPLIED  -- a pointer button was pressed down --
      onmouseup   %Script;       #IMPLIED  -- a pointer button was released --
      onmouseover %Script;       #IMPLIED  -- a pointer was moved onto --
      onmousemove %Script;       #IMPLIED  -- a pointer was moved within --
      onmouseout  %Script;       #IMPLIED  -- a pointer was moved away --
      onkeypress  %Script;       #IMPLIED  -- a key was pressed and released --
      onkeydown   %Script;       #IMPLIED  -- a key was pressed down --
      onkeyup     %Script;       #IMPLIED  -- a key was released --"
      >
    Code (markup):
    But again, there's a reason I like the WDG's rapidly aging guide since it takes the specification and turns it into plain English. Case in point:
    http://htmlhelp.com/reference/html40/attrs.html

    I think a lot of people who THINK they know HTML need to sit down and read the entire WDG HTML 4 reference end to end. It does far more to teach you what things are for than most 'tutorials', and is far more comprehensible than the specification.
    http://htmlhelp.com/reference/html40/
     
    deathshadow, Mar 31, 2013 IP