class (Object) vs id - javascript

During the web development i encountered with many problems and resolved it but these problems gave me a thought which i want to share and would like to know your view.
Which One is efficient Class Or ID : Both has own specification but i think Class is more convenient over ID (if you are dealing with thousands of IDs.)
I know Id is quite efficient for DOM Traversing but what if you have hundreds of elements with IDs, How do you manage ?
Using CLASS : One class can be derived by many elements and the individual elements can be dealt by using "this" object.
I am curious to know your view OR how do you handle the project/projects when you have many-many elements with ID or Class name
<div class="example" onclick="function click(this);"> </div>
<div class="example" onclick="function click(this);"> </div>
<div class="example" onclick="function click(this);"> </div>
function click(obj){
alert(obj.classname + "We can access any individual element by using Object");
}
<div id="exm_1"> </div>
<div id="exm_2"> </div>
<div id="exm_3"> </div>
but in case of ID, we go through each ID

I liked a few guidelines that are put together by one of my managers, I would like to mention them here:
Start with the following common sense guidelines, and apply them to both JavaScript selectors and CSS selectors.
Use an ID if:
You are certain that the element only
appears once in the whole page.
The desired style or JS behavior is
specific to only one area of the
whole page.
Typical ID Examples:
Large container divs for entire
sections of the page ("#interior",
"#global-status", "#tree-container")
Links or buttons with special names
and purposes ("#add-new-report",
"#preview-popup")
Use a class if:
It is possible for the element to
appear multiple times in the same
document.
The desired style or JS
behavior is general and is applicable
to multiple elements.
Typical Class Examples:
Reusable interface patterns
(".action-links", ".title-bar",
".h1-with-border")
Element states
(".current-selected", ".highlighted")

You should follow this general guidelines:
2) Use a class when you need many elements to share some common behaviour, or when there's currently only one element but you're not sure if there will be more with the same behaviour in the future.
1) Use an Id when an element needs unique identification and you're sure there will be only one with it (think in the future code changes). There should never, never be 2 or more elements with the same id.
Hope this helps. Cheers

Related

jQuery child elements with same ID

Imagine that I have this HTML structure:
<div id="bodyRead">
...
<div id="List"></div>
</div>
...
<div id="bodyWrite">
...
<div id="List"></div>
</div>
As you can see, I have the #List inside two different divs (bodyRead and bodyWrite). For a lighter code, I preferred to work with id instead of class (even knowing that duplicate IDs isn't valid, the code makes more sense to me), and selecting the #List on jQuery like this:
$('#bodyRead #List').off('click').on('click', function() ...
$('#bodyWrite #List').off('click').on('click', function() ...
works. I'm always taking care of make duplicate IDs only on child divs, where I can separate them by their parent div on jQuery selector.
Is this approach very wrong? I mean, this can get me in trouble?
don't duplicate your Id even in child element .. change it to class="List"
then you can use
$('.List').on('click',function(){
var getparent = $(this).parent().attr('id');
alert(getparent);
});
and if class="List" not first level child of any of #bodyRead or #bodyWrite
add class to it
<div id="bodyRead" class="mainDiv">
<div id="bodyWrite" class="mainDiv">
and then use
$('.List').on('click',function(){
var getclosest = $(this).closest('.mainDiv').attr('id');
alert(getclosest);
});
You should expect that CSS and JavaScript (including jQuery and other frameworks) behave in accordance with the HTML specifications. ID must be unique, multiple instances of the same ID is not supported. See below:
From HTML 4.01 spec:
id = name [CS] This attribute assigns a name to an element. This name
must be unique in a document.
class = cdata-list [CS] This attribute
assigns a class name or set of class names to an element. Any number
of elements may be assigned the same class name or names. Multiple
class names must be separated by white space characters.
http://www.w3.org/TR/html401/struct/global.html#h-7.5.2
This is from the HTML 5 spec:
3.2.5.1 The id attribute
The id attribute specifies its element's unique identifier (ID). [DOM]
The value must be unique amongst all the IDs in the element's home
subtree and must contain at least one character. The value must not
contain any space characters.
There are no other restrictions on what form an ID can take; in
particular, IDs can consist of just digits, start with a digit, start
with an underscore, consist of just punctuation, etc.
An element's unique identifier can be used for a variety of purposes,
most notably as a way to link to specific parts of a document using
fragment identifiers, as a way to target an element when scripting,
and as a way to style a specific element from CSS.
Identifiers are opaque strings. Particular meanings should not be
derived from the value of the id attribute.
Well i feel this is a bad approach because the browser creates the DOM(document object model) for the page, which takes into consideration that each Id has a unique value.It would be hard to play with the duplicate Id's in javascript when you want to manipulate you need to consider parent as well as child id each time. So its better to use classes instead.
Although id selectors are meant to be unique your code will work as long as you make sure to use correct nesting. In other words #bodyRead #List and #bodyWrite #List are perfectly fine as long as you don't create ambiguity by leaving out the parent selectors to #List.
Still, using multiple identical ids on the same page is just asking for trouble. You should reconsider switching to class selectors or reevaluate if it is really worth the potential trouble of sticking with your original idea.
You certainly should not use duplicate id's in an html page. If you have a similar concept within two different div's then class makes more sense anyway. So change the List ids to classes and then you can access them like this:
$('#bodyRead .List').off('click').on('click', function() ...
$('#bodyWrite .List').off('click').on('click', function() ...
Even if your code works now due to how jQuery works, because the html specifications say not to do this, you can not know for certain that your code will continue to work in the future.

JQuery "#id.class" Selector Mashup

I have some bullet points which I want to show more text below them on clicking them. They are both two separate Ps that are paired together by sharing a common id. So, what I am trying to do below is to find the element with (id_same_as_this.class), so that the element with the class "expand" as well as the id that matches the clicked on P is toggled. Does that make sense?
$(document).ready(function(){
$(".expandable").click(function(){
$(this.attr('id')+"."+"expand").toggle(800);
});
});
I only ask if the above code could be made to work because it would make the expandable bullet points in my web page significantly less code intensive than a lot of the examples I have read about.
$(this.attr('id')+"."+"expand").toggle(800);
Must be
$("#" + this.id +".expand").toggle(800);
You missed the # there. That said, you shouldn't ever have a common ID. By definition IDs are meant to be unique. If you have the same ID on multiple elements, while it may work now on the browsers you try, you have no guarantee it won't break in the next rev of jQuery (or Chrome, or Konqueror, or iOS Safari). There's also no reason to do it. You could just use classes or data-* attributes.
Yes this will work but you need a # before the ID
They are both two separate Ps that are paired together by sharing a common id.
IDs are unique. Two elements can't share a common ID, as that defeats the whole purpose of having a unique identifier. JavaScript assumes that you're using valid HTML, so document.getElementById() will return only the first element with a matching id. By using non-unique IDs, things will start breaking in unpredictable ways:
$('#foo').find('.bar') // Won't search past first #foo
$('#foo .bar') // Will search past first #foo in IE8+
Try restructuring your HTML to make this task easier. Maybe you could do something like this:
<ul id="bullets">
<li>
<h2>Title</div>
<div>Text</div>
</li>
</ul>
And then use a simple event handler:
$('#bullets h2').click(function() {
$(this).next().toggle(800);
});
You don't need id values for this at all (which is good, as from the comments on hungerpain's answer, you're using the same id value on more than one element, which is invalid).
Just do this:
$(document).ready(function(){
$(".expandable").click(function(){
$(this).find(".expand").toggle(800);
});
});
That will find the element with the class expand within the expandable that was clicked. No relying on unspecified behavior of selectors.
If you really need that data on the expandable, just put it in a data-* attribute. So instead of this invalid structure:
<!-- INVALID -->
<div id="foo27" class="expandable">
<div class="expand">...</div>
</div>
<div id="foo27" class="expandable">
<div class="expand">...</div>
</div>
Do this
<!-- VALID -->
<div data-id="foo27" class="expandable">
<div class="expand">...</div>
</div>
<div data-id="foo27" class="expandable">
<div class="expand">...</div>
</div>
Use the above code to do the expansion. If you need the value, use .attr("data-id") or .data("id") to get it.

Separate ID and Class for JS and CSS

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.

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