Separate ID and Class for JS and CSS - javascript

In several jquery tutorials, separate ID and Class are used for JS and CSS. for example
<div id="test" class="test">TEST</div>
As ID is used in the jQuery code, and Class is used in CSS. To me it is easier to not introduce Class and use ID for CSS rule too. Is there any advantage to use css-less ID for javascript?
EDIT: Thanks folks! I know the difference between ID and Class; I am asking why some use separate ID and Class for JS and CSS when one is sufficient. Here, the matter is the necessity for uniqueness of ID. The case is separating JS and CSS tasks (while they are closely entangled).
EDIT2: As requested, I give a typical example: this Tutorial. Look for actionsBox; .actionsBox has been used for CSS and #actionsBox for JS. As you can see there is only one <div> so ID would be enough for styling.

Read “Don't use class names to find HTML elements with JS” for some reasons why you may want to avoid using classnames in JavaScript.
This all boils down to personal preference, really.

Edit: #Sharon commented a link to a great article that discusses the drawbacks of using id selectors in CSS.
One reason people might only use classes in CSS is the specificity of the id selector.
If you’ve got two style declarations for one element, and they specify different values for a property, then the style declaration with the more specific selector wins out.
For example:
HTML
<div id="test" class="special-test"></div>
 CSS
#test {
color: red;
}
.special-test {
color: blue;
}
The ID selector trumps all other selectors for specificity (see http://www.w3.org/TR/selectors/#specificity for the rules), so here, the <div> will be red.
People who added class="test" to the <div> would presumably have written this:
HTML
<div id="test" class="test special-test"></div>
 CSS
.test {
color: red;
}
.special-test {
color: blue;
}
When both style declarations have selectors with the same specificity, the later declaration wins out, so here the <div> would be blue.
Personally, I’ve never found that to be a problem. In the first example, all you have to write to make the <div> blue is this:
#test.special-test {
color: blue;
}
But I guess some people find this aspect of specificity unnecessarily complex, and so avoid it by only using class selectors in their CSS.
(And I assume they keep the id because it’s faster to retrieve a DOM element in JavaScript by id than by class.)

You can use both ID and Class with both javascript and css. For example:
CSS
/*ID as identifier*/
#some_id {
<css attributes>
}
/*Class as identifier*/
.some_class {
<css attributes>
}
Javascript:
/*Get by ID*/
document.getElementById("some_id");
/*Get by class*/
document.getElementsByClassName("some_class");
The difference between the two is that ID will, or at least should be, unique and therefore will only affect or return a single element when applying css rules or selecting via javascript respectively. Class on the other hand is for affecting or selecting elements of a similar nature or classification.
If you had a car park with ten cars in it and you were to say "I want the car in space number three" you'd expect a single return whereas were you to say "I want the Fords from the car park" you'd expect to return every car in the car park which was a Ford. Css and javascipt use of ID and Class is no different.
EDIT: As per the OP's new redefined line of questioning.
css and IDs:
Css can harness IDs as an anchor so that the contents of a uniquely identified DOM object. Consider the folowing piece of css.
#some_id tr:nth-child(odd) {
background-color:#666888;
}
In the above example the css is tied to a unique identifier which in this case the ID is assigned to a table but the css rules themselves are applied to the odd rows within the table. In other words the css in this case affects table row elements where TR itself is an object class (not to be confused with css class).
In short, for ID at least, it is useful to use IDs within css and when you consider that jQuery and the likes of support Class-based queries using Class for selection within javascript is also useful.

Curious about the dual nature of "ID" in javascript and CSS. If you visit this example from w3schools: http://www.w3schools.com/js/tryit.asp?filename=tryjs_blocks
you'll see the which is "naming" this particular <div> with the name "myDiv". This is because javascript getElementById("myDiv") is used later to modify the text contents of this specific <div>
BUT - if you add the line of code:
<style> #myDiv { color:blue; } </style>
you now have a CSS id with the same name as the javascript <div id>
The sample code in the w3schools does indeed change the color of the <div> called "myDiv" to blue. But when you push the "try it" button on that page, the CONTENTS of the javascript <div> also changes, which is the point of the w3schools example. Ie., it's teaching you that getElementById("myDiv") is how you can retrieve and modify contents of a named <div>
But because the identically named CSS #myDiv id is in force the <div> contents are changed, and they remain blue due to the style sheet.
So when you see a <div id="myDiv"> inside an HTML page, how can you readily tell if this <div> wants CSS id treatment? Or if this <div> will be referenced by some javascript getElementById() method?

Maybe you should check out the differenc between ID's and Classes:
http://css-tricks.com/the-difference-between-id-and-class/
I have never heard of using classes only in CSS and ID's only for JavaScript.
The main thing is ID's are unique, thats why they are called identifiers. If you have the same styling of a div over and over again on your webpage you should use a class to style them.
EDIT: It's not common or maybe its not allowed, I'm not sure, that ID's start with a number !

You can use id and / or class in JS and / or CSS. It all depends what you want to select. If you want to select a single DOM element, feel free to use id. If you want to select a group of related elements you might be better off using class.

Id should(read: must) be unique. A class is a set of object that have similarities, for example all lists on the page should look the same (but then you should use the list selector instead of a seperate class for it.
They have different purposes.

Related

I can't find any documentation on this CSS selector.. what is it?

I am using jQuery to change the width of a sidebar, and within the working code on CSS it shows this:
#wrapper.MenuDisplay #my-sidebar-wrapper {
width: 200px;
}
But after looking through w3schools and mozilla etc, I have not found any selector which looks like #foo.bar.
The reason I am trying to figure this out is that I can't understand why this CSS isn't applied straight away, and how a jQuery toggleClass is able to get this width to be applied (which it successfully does) on a button click.
Does anyone know what is going on here? What the selector is and why it works after clicking on a jQuery button but not straight away on page load?
Many thanks
That means element with id foo and class bar, shortened to #foo.bar
[id][class]
#wrapper is id of an element, and .MenuDisplay is class. Element must have that id and class to get that CSS work.
#foo.bar
matches an element that has both id = "foo" and class = "bar".
It appears you are asking what a sequence of selectors means.
According to current W3C standard, it is...
...a chain of simple selectors that are not separated by a combinator. It always begins with a type selector or a universal selector. No other type selector or universal selector is allowed in the sequence.
Not everyone considers the second sentence of the definition true, because, for example, #this or .that appear not to begin with either a type selector (a, div, span, etc...) or a universal selector (*). However, one should bear in mind that...
...whenever a sequence of selectors does not begin with a type or universal selector, it "defaults" to starting with an omissible universal selector.
So, #this is a shorthand for *#this, .that is a shorthand for *.that. And #this.that is a shorthand for *#this.that.
In fact, if you read the entire universal selector paragraph, you'll notice a note at its end recommending it not to be omitted.
However, almost nobody respects this recommendation and, in practice, the only time you'll see a universal selector is when someone wants to give a CSS property to every single element in the page.
Like in * {box-sizing: border-box;}
As a side note, not omitting the universal selector in your CSS is supposed to make it faster. This is not difficult to test and appears to be true, but the differences are negligible.
Well As far as I can understand from your question,
jQuery Selectors allow you to select and manipulate HTML element(s) or select HTML elements based on their name, id, classes, types, attributes, values of attributes and much more. It's based on the existing CSS Selectors, and in addition, it has some own custom selectors.
In this case:
#foo.bar points to an element in the DOM that has an id="foo" and a class="bar".
jQuery Selector Tester to demonstrate the different selectors:
jQuery Selectors Test Page
Hope I could help!
#foo.bar refers to the element with together foo id and bar class.
$('#foo.bar').fadeOut('slow');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='foo' class='bar'>box</div>

Use JavaScript to rewrite CSS with class and tag at the same time

I am able to easily change the style or the tag of an element based on certain criteria using JavaScript:
document.getElementsByTagName("mainclass")[0].style.color:#ffffff;
However, is there a way to do this is the style contains multiple classes and a tag like so
.mainclass .secondaryclass div td {
color: #000000;
}
The following is not working for me so im sure there is a totally different way of doing it:
document.getElementsByTagName(".mainclass .secondaryclass div td")[0].style.color:#ffffff;
...
The other option if easier is to figure out how to use JS to embbed a external style sheet (and not at the end of head, just where the JS code is thats where the CSS should go)
Thanks!
getElementsByTagName does not accept CSS selector syntax. You're looking for querySelectorAll but you'll have to iterate over the returned list to assign the style, and it's not completely supported across browsers.
...which is why everyone uses jQuery.
Example, assuming you want to modify just the first matched element:
document.querySelectorAll(".mainclass .secondaryclass div td")[0].style.color = '#ffffff';
Note the change from : to =, and wrapping the color value in quotes. JavaScript has different syntax from CSS; I suggest that you take some time to learn it.

Removing effect of a CSS selector

My requirement is a bit tricky. I have a mark-up as below: (just an example, real mark-up is very complicated)
<div class="classA">
<div class="classB">
<p class="classC">
<span class="classD">
</span>
</p>
</div>
</div>
As you can see above, there are four CSS classes classA, classB, classC, classD associated with the markup.
Also I have used jQuery to bind events using these selectors.
My Requirement: I want the jQuery event binding to work and at the same time, the CSS should not get applied i.e. I want to negate the impact of CSS styles from a UI perspective, but from functional perspective jQuery event handlers should still work.
So, is it possible to override the CSS selectors such that their styles don't get applied to my mark-up elements ?
example below:
div.classA div.classB p.classC span.classD{
color:red;
}
I don't want the font color to be red, so I tried to override the selector as follows, but its not working:
div.classA div.classB p.classC span.classD{
color:red;
}
div.classA div.classB p.classC span.classD{
/*no styles here*/
}
Please help !!
Then just delete those classes from css. jQuery will still work though.
There is no requirement that only classes used in css have to be used in jquery.
For example:
<div class="someUnknownClass"></div>
Even though, there is no someUnknownClass defined in css, $('.someUnknownClass') will still work.
Use another class name for the selector. So you have classA for the css and classX for the selector.
If you don't want the styles applied. Then you could use $('selctor').css(); to over write the styles. Bit hacky!
OR.
Add a class that over-rides the css. Or remove the class that holds the css.
using: $('selctor').addClass('no_styles'); OR $('selctor').removeClass('current_styles');
I don't know any mechanism allowing to do that the way you want it.
the work around i would suggest would be binding your events on anoter css class and doing something like this :
$('.classD').addClass('eventClassD').removeClass('classD');
$('.eventClassD').on('myEvent', function(){...});
like this you will still have events binded to your elements and would get rid of all the css.
You want to do it without modifying the JS? There's no clean way to do that. But try this.
Presumably you will have something that distinguishes this special set of elements to distinguish it from other elements, of which styles' you want to retain. This is difference probably manifests itself in the form of a different parent container. Just copy the set of CSS rules that affect these classes, and prepend this parent CSS selector with the pre-class values.
"Basically, I do not want to touch the js code, and only if something can be done on the css front, then my requirement is achieved."
If that is all you need, then just remove all of the css definitions from the page.
$("link,style").remove()

Is it normal to have two elements with same id in two div elements with other id?

I know, that two elements can't hav the same id. But it's happens so, that in my project I have two elements with same id in other divs, like this
<div id="div1">
<img id="loading" />
</div>
<div id="div2">
<img id="loading" />
</div>
And CSS:
#div1 #loading
{
some style here...
}
#div2 #loading
{
another style here...
}
Works fine for me, but maybe it is not reccomended to do by so?
Yes, I know, thet I can use classes, and it's strongly recomended to do by so, but I want to know is there any potential risk in this usage of id?
I think no, because when I wrote for example
$("#div1 #loading")... it becomes a unique element.
Isn't it?
Change your id to class. It is not a good idea to give duplicate id.
Think two students having same roll no in a class. Imagine them getting examination result. How will the school be able to recognise the marksheet?
Your way is not cross browser compatible, and will affect a lot while coding JavaScript, and posted form etc
You can get the same effect using class
see
<div id="div1">
<img class="loading" />
</div>
<div id="div2">
<img class="loading" />
</div>
and css:
#div1 .loading
{
some style here...
}
#div2 .loading
{
another style here...
}
an id must (should) be unique!!
you will have troubles selecting it via JS in most browsers -
better use class
The big reason is for JavaScript DOM manipulation. In your case, if you do something like this...
document.getElementById("loading")
... JavaScript will return the first element, and the first element only. You'll have no way to access the rest of them without some serious DOM walking.
Just because no-one else has posted it - the HTML spec, section on ID, which says:
id = name [CS]
This attribute assigns
a name to an element. This name must
be unique in a document.
Yes you are right, it is not recommened to do so. An ID should always be unique (e.g. if you want to select the element with javascript).
If you just want to add the same style to the divs, just use css class.
Unique:
In mathematics and logic, the phrase "there is one and only one" is used to indicate that exactly one object with a certain property exists.
#div1 #loading does not remedy the fact that you have two instances of #loading in your document. So, no, don't do that.
IDs should be unique, so id1 and id2 are fine, but for many elements with the same style, use an HTML class and CSS class selector:
.loading
{
styles here
}
These are allowed to be repeated as many times as you want on a page :)
Is it normal? No.
Is it recommended? Definitely not! It's actually prohibited (but enforcement is weak).
But it (apparently) works, so ...
Id are used to distinguish elements, they must be unique for different reason, one of them is the use of javascript, function like getElementById won't work well if you have duplicate ID, you won't be able to predict what it'll do on different browser as JS is self-implemented on each browser differently.
If you wish to use a structure like #div loading and #div2 loading it seem clear that both loading have similar uses so they should be classes and would be used like this
#div1.loading and #div2.loading
Also one plus of using this syntax would be to put the common style in .loading like this
.loading{ style common to both the loading }
#div1.loading{ style used only by the loading in div1 }
#div2.loading{ style used only by the loading in div2 }
https://www.w3.org/TR/1999/REC-html401-19991224/struct/global.html#adef-id
BUT!
If you need it in your project, you can use it, like suggested in my Question Final Update!
validation and purist-ism aside, it is perfectly functional. But I would definitely be annoyed if I use that #loading id and find that a jquery effect or a css effect applies to more than 1 element.Do tell me if IE6 or 7 or Firefox 1.x or 2.x ruins that code.
It's bad practice of using I'd on element. Because I'd giving something for understanding unique with their name identification. And second thing we use its in CSS but in JavaScript this bad practice. So good example for this class and student.
So don't do this.
I disagree on people saying to always use a "unique", meaning different ID everytime you label one. Sometimes its acceptable, such as my case where I am making a calculator.
The javascript is doing the math and outputting the result into the div with the id="total". I need that same exact "total" to be in 2 different places however. In this case, why wouldn't I use two different div's with the same ID? I need the same number in both boxes. With jQuery, I perform and output the math once and it populates both div's at the same time, which is what I want.
So long as you understand the risks where if you were PULLING information from those 2 div's with the same ID, then I say feel free. As long as you dont confuse yourself and need 2 different results in the same div ID.

What are the reasons to use the id attribute for CSS purposes? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I've always used the class attribute, never id for the purpose of CSS selecting and styling. I know that the id must be unique, but that doesn't seem to be a reason to use it for CSS.
The only reason I have used the id attribute is for JavaScript and form labelling.
I find mixing id and class for the purpose of CSS can cause confusion, and for me it's a good way to force separation of style and behaviour.
Is there a good reason to use id for CSS purposes? Is there anything that can be achieved with id that can't be done with class?
Comments I found useful/interesting
You could say the same thing about classes. There's lots of JavaScript out there that does (and must) target elements of a specific class. Changing the class in those instances is just as problematic from a behavior standpoint. - AaronSieb
IDs have different specificity in the cascade than classes. - Killroy
Using ID for styling makes sense if it's an element that doesn't have duplicate, especially if it's something that shows up in all/most pages - RichN
Using ID for styling makes sense if it's an element that doesn't have duplicate, especially if it's something that shows up in all/most pages.
E.g.:
Page header & footer
Search box (the thing you can see up there)
Navigation list (something like the thing on the right)
Selecting anything with a unique id is faster than selecting with a class. The difference is negligible, but in applications with huge amounts of DOM elements, or intensive Javascript application, it makes a difference.
For example if you are using jQuery check this out: jquery performance rules
No, but if your element has an id why not use it for styling?
You could say the same thing about element names - there's nothing you can do with p that you couldn't do with class='paragraph'. That doesn't mean it's a good idea to add class='paragraph' to every <p> element.
IDs identify, classes classify. This point has been mentioned several times here, more or less.
An example would be:
<div class="author" id="stephen">[...]</div>
From a CSS specificity standpoint, targeting IDs will make CSS rules more specific than rules with classes, even several classes.
Thus:
p#recent {}
is more specific than
body>p.news.recent {}
and when a user agent finds both of these, the first will prevail.
The main reason I use ID tags is to communicate with people who are reading my code. Specifically, the ID tag makes it easy to reference whatever specific element they want to with complete peace of mind, knowing that any changes they make to it will only affect that one element.
There is also a more technical reason to use ID tags that you may not know. This information can be quite enlightening for those who are new to CSS.
The following outline illustrates exactly how the "cascading" nature of Cascading Style Sheets works. In this outline, start by comparing 2 CSS styles based on the uppermost criteria of the outline, ie "1. Winner = !important declaration." If one style is of higher priority than the other in that aspect, it wins. If they are the same in that aspect, continue down to the next criteria in until you find the differentiating factor.
Winner = !important declaration.
Eg. #some-element {color: blue !important;} beats #some-element {color: red;}.
Winner = Inline CSS.
Eg.:
<div id="some-element" style="color: yellow;}">some content</div>beats...
<style type="text/css">#some-element {color: red;}</style> and...
<link type="text/css" link rel="stylesheet" href="set-some-element-color-to-blue.css"/>.
Winner = Greatest # of ID selectors.
Eg. #some-element#id-2 {color: blue;} beats #some-element {color: red;}.
Winner = Greatest # of class, pseudo-class, and other attribute selectors.
Eg. .some-elements.class-2 {color: blue;} beats .some-elements {color: red;}.
Winner = Greatest # of element names and pseudo-elements in the selector.
Eg. #some-element:hover {color: blue;} beats #some-element {color: red;}.
Winner = Most recently read by the machine.
Eg.:
<style type="text/css">#some-element {color: red;}</style> beats...
<link type="text/css" link rel="stylesheet" href="set-some-element-color-to-blue.css"/> because internal CSS is read after external CSS.
You don't HAVE to use IDs. There is no design that you can create using IDs that you can't create using classes.
With that said, using an ID has the advantage of clearly labeling a selector as applying to exactly one element in a page. I typically use them for styling elements in my page templates (#Content, #Navigation, etc.).
In general, I would try to use it in areas that allow me to make the markup more concise. When a selector can be targeted at a tag, you should use the tag. When it can be targeted at an ID, use the ID. Otherwise, use a class.
But, again, whether or not you use IDs isn't terribly important.
I tend to think of the relationship of id and class in HTML as analogous to object-oriented programming: an id is like an instance of a class.
I use classes more than I use ids, and often use multi-class selectors (e.g. .film.drama). But if I do want to identify a particular element, so that I can apply specific styling or behaviour, then I'll assign an id, and often a class as well. E.g.
<ul>
<li class="film drama">A</li>
<li class="book drama">B</li>
<li class="film documentary" id="film-9832">C</li>
</ul>
In assigning an id, I think "could it ever make sense for there to be more than one of these on the page". If the answer is yes, then I'd probably go for a class instead.
As a result, and as #RichN and #AaronSieb have mentioned, I often use id's for specific page elements that are certain to be present only once on the page:
<ul class="sidebar" id="site-meta">[...]</ul>
If you have multiple elements of the same class and need to specify a different style for one or more of them that'd seem pretty valid to me.
The only thing I can think of to use an ID is if you have a specificity war - two elements with the same specificity. Applying an ID will give your element a higher specificity - +100 to be exact.
So, in the case where you have two styles defined with equal specificity, you may want to 'clobber' one by applying a higher specificity to the other. That being said, you can achieve the same by applying a more specific class to that selector too, which would increase the specificity by 10.
ID = 100 (#foo)
class = 10 (.bar)
element = 1 (div)
IMO, using ID-based styles is a bad idea.
IDs, being unique, should only occur up-to 1 time within your DOM. This limits the use of any ID-related style to up-to 1 time.
CSS classes, on the other hand, can be used multiple times or not at all.
Frankly, I think ID should be used for behavior, and class should be used for style. The fact that you can use them interchangeably is part of what makes some aspects of web development inconsistent.
I use a id when i know im going to use javascript on that specific element. ID's are much faster then classes in javascript.
I personally prefer to use ID's for static page elements (headers, footers). Reason being page weight.
id="h" is lighter than class="h".
Every byte counts in my opinion.
The main reason why I use ids in CSS is for layout. If I have one header and footer, then:
#header
{
...
...
...
}
#footer
{
...
...
...
}
Or one wrapper for my main content, or one right sidebar. If someone decides they like my layout and want to view source, it's easy to see.

Categories