Javascript/HTML: Using id vs. class when naming - javascript

I am starting to learn some Javascript using Meteor and am looking at their examples.
One bug that tripped me up for a bit happened when I was adding a text-field for input with a button next to it; users would type in a name they wanted to add to a list and then click the button to actually add it.
My question is: why does it seem to be the case that in the html, the text field has to be named with id="..." while the button has to be named with class="..."?
For additional reference, in my javascript file, I am using textfieldname.value and 'click input.buttonname'. Does the id vs. class requirement stem from how I'm using them?

The "id" attribute is used to supply a globally-unique identifier for an element. The "class" attribute is used to categorize or typify an element according to its meaning, its intended use, its relationship to other elements, or whatever else your application requires.
Usually it's more flexible to use classes to identify things, because more than one element can be given the same class, and an element can have as many classes as are needed. Any single element may only have one "id", and the values must not be re-used in the same document. There are clear use cases for both attributes in which one or the other is obviously more appropriate, and many other cases where it's less clear and for which either could be used.
This isn't really a JavaScript issue so much as a "web application design" issue. How one labels HTML elements is dictated by the nature of the content (HTML), the needs of the presentation (CSS), and the intended behaviors (JavaScript).

Related

Is giving elements an id within a html template okay?

I feel like the answer is an obvious 'no', but I've seen it done in tutorials and am curious if the side effects are what one would expect.
HTML 4/5 specify that ids should be unique document wide, but are still forgiving on the matter. How might the browser respond to dynamically injected elements that may have been given ids in their respective template? Is it encouraged to just use classes for elements in templates? If ids are okay, then how is it handled by the browser?
Ids are unique which is used to apply styling or some particular task for that particular element.
when we inject dynamically the html structure that ID name on element should be unique then only that styling and the manipulation will work
You can insert as many Ids in the Single page and the browser will handles that properly depending the elements which you will inject
Remember that ID are use for only one tag.so whatever will be the styling of manipulation will added that will work for that ID only.

Should I be using classes more than ID's when utilizing jQuery?

As a new web developer, I've been utilizing a lot of resources like StackOverflow to assist me in the learning and development process.
When using jQuery, all of the examples/responses that I've come across so far have only referenced classes, like so:
$('.yourClass')
as opposed to
$('#yourID')
Seeing that class referencing seems to be the trend (I honestly haven't found one author who writes a jQuery to an ID), are there any pitfalls I should be aware of for using ID's w/ jQuery or JS in general? Thanks!
EDIT 1: I'm aware that ID's are for single-items, classes are for accessing multiple items. I'm more interested in why I don't see any jQuery or JS examples referencing ID's. Thank you!
You would have to ask each author on a case-by-case basis, but generally when creating examples, the selector used doesn't matter; what's important is that you have a jQuery collection that you can call a method on.
By using a class selector in the example, you avoid newbie developers claiming that your plugin doesn't work when they try to use it on multiple elements with the same ID. Your example serves the purpose of showing how to use it on one or more elements, rather than just one.
People like to use classes because ids have to be unique across the whole page. When trying to make reusable, pluggable components, id's make this impossible to enforce.
Exception: the new web-components standard allows you to encapsulate ids to just your component.
An ID must be unique, you can have only one (like highlanders).
Classes are used to identify a "type" of object not a specific one.
An obligatory car analogy:
An ID is a license plate, unique to one specific thing #345-abc
The class relates to a whole category of things like .truck
Take note that a selector like $(".something") will actually be capable of producing a list of DOM elements; as it will select all DOM elements with the class of "something"
An ID selector $("#unique") will only ever return one element
Think of your HTML and CSS first.
Using Classes
If you have multiple HTML elements which all will look, feel and behave in the same way, then it is highly recommended to use a class to represent their style and behavior.
Example: rows or columns on a table, navigation buttons which animate in the exact same way, wrapper to images which have the same size throughout your website, etc.
Using ID's
However, if you have a unique HTML element which represents a particular thing or state or action in one of your pages, then that element should contain an id.
Example: pop up modal, a unique looking button, unique sections on your website which you can navigate to by their id, etc.
Then, you can use this behavior in your JavaScript and jQuery or whatever else you like to use.
Further reading
I know that you are fully aware of why we should use ID's or classes.
But the vast majority of answers that are given here, are thinking of a project context.
So, let's say editing a .js file that is linked to the scope of the entire project, the idea here is to be as reusable as possible, so that's why you'll see much more classes references than ID's. Is hard to maintain a project js file that makes reference to different ID's that are abroad the project.
Same thing will apply to css.
I hope the answer is enough, be free to post a comment or suggestions. :-)

Local id-s for HTML elements

I am developing a kind of HTML+JS control which can be embedded into various web pages. I know nothing about those pages (well, I could, but I don't want to). The control consists of one root element (e.g. DIV) which contains a subtree of child elements. In my script, I need to access the child elements. The question is: how can I mark those child elements to distinguish them?
The straightforward solution is using id-s. The problem here is that the id must be unique in the scope of the entire document, and I know nothing about the document my control will be embedded into. So I can't guarantee the uniqueness of my id-s. If the id-s are not unique, it will work (if used with care), but this does not conform with the standard, so I can meet problems with some new versions of the browsers, for example.
Another solution is to use the "name" attribute. It's not required to be unique -- that's good. But again, the standard allows the presence of "name" attribute only for a restricted set of element types. For example, the "name" attribute is invalid for DIV elements.
I could use, for example, the "class" attribute. It seems to be OK with the standards, but it's not OK with the meaning. "class" should be used for other purposes, and this may be confusing.
Can anybody suggest some other options to implement local id-s for HTLM elements?
You could use the HTML5 data-* attributes so you can give them a custom name with the right meaning:
https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes
Do something like:
<div id="element-id" data-local-id="id-value">
...
</div>
and get the value in JavaScript with:
const el = document.getElementById('element-id');
const { localId } = el.dataset;
If you use a prefix to all of your ID's and or classes such as myWidgetName_98345699- the likelihood of collisions is highly improbable.
<div id="myWidgetName_98345699-container" class="myWidgetName_98345699-container">
jQuery does have selectors that will search for part of an ID, so using common names like container would be smart to stay away from as well. Using a longish alphanumeric mix for the specific part of the ID would be smart also
Typically, including hidden information within the web page required creative approaches. For example:
Storing information within HTML element attributes such as id, class, rel, and title, thus overriding the attributes original intent.
Using <span> or <div> blocks that contain the information, while making such blocks invisible to the user through styling (style="display: none;").
Adding JavaScript code to the web page to define data structures that map to HTML ID elements.
Adding your own attributes to existing HTML elements (breaking the HTML standard itself, and relying on the HTML browser to ignore any syntax errors).
The approaches above are not elegant and are not good coding practice, but the good news is that jQuery has a facility that simplifies associating data to DOM elements in a clean, cross-browser manner.
Use the custom data attributes:
Any attribute that starts with "data-" will be treated as a storage area for private data (private in the sense that the end user can't see it - it doesn't affect layout or presentation.
Defining custom data via html:
<div class="bar" id="baz" data-id="foo">
...
</div>
Associating data-id to specific DOM elements (jQuery):
$('#foo').data('id', 'baz');
Retrieving an element with specific data-id:
var $item = $('*[data-id="baz"]');

How to avoid locking my HTML structure when using jQuery to create rich client experiences?

I've had this happen to me three times now and I feel it's time I learned how to avoid this scenario.
Typically, I build the HTML. Once I'm content with the structure and visual design, I start using jQuery to wire up events and other things.
Thing is, sometimes the client wants a small change or even a medium change that requires me to change the HTML, and this causes my javascript code to break because it depends on HTML selectors that no longer exist.
How can I avoid digging myself into this hole every time I create a website? Any articles I should read?
Make your selectors less brittle.
Don't use a selector by index, next sibling, immediate child, or the like
Use classes so even if you have to change the tag name and the element's position in the HTML, the selector will still work
Don't use parent() or child() without specifying a selector. Make sure you look for a parent or child with a specific class
Sometimes, depending on the amount of rework, you'll have to update the script. Keep them as decoupled as possible, but there's always some coupling, it's the interface between script and HTML. It's like being able to change an implementation without having to change the interface. Sometimes you need new behavior that needs a new interface.
I think the best way to help you is for you to show a small sample of a change in the HTML that required a change to your jQuery code. We could then show you how to minimize changes to JS as you update the HTML

javascript name vs ID

As far as I know there are two ways to get the value from a textbox either
document.formName.textboxName.value;
or
document.getElementbyId('textboxId').value;
As I understand using form name would mean I have less code to write, as name can be used for posting data and getting the value (apart from using ajax). As where if I was just posting using a standard form I would use name to post but I cannot use id ?
e.g. in php I would use
$_POST['texboxName'];
If I where to have and ID on the textbox I cannot get the value using php ?
Which is the standard recommened way of doing this, and is using name browser friendly? Links if possible please, thanks.
The ultimate guide in this is the HTML specification.
Things that stand out there:
id is valid for any HTML element, while name only applies to a select few (a, input, textarea and maybe a few others).
An input (and textarea) element requires the name to be set if you want it to be submitted.
The name attribute is used during submitting the form, i.e. to create a name-value pair that will be processed to the server. The id attribute is used to locate and element in the DOM. Usually the name is used only on the form elements
References:
http://www.w3.org/TR/html401/interact/forms.html
http://www.w3schools.com/html/html_forms.asp
I typically use both. As you mentioned, name is useful for using the data via JavaScript and also once it has been submitted. Feel free to use additional characters in the name as needed: I tend to use []s in my names when the input will be used in an array server-side.
The id attribute can be used for accessing the element via JS/the DOM. It is also used by <label>'s for attribute. If you do this with checkboxes, for example, clicking on the label will cause the box to become checked. That's a big plus for usability.
I consider it good practice to have a name and id for each form element. The reason being that if you want to add labels, or styling via sytlesheets (which you should be doing), then it makes sense to have both.
As for accessing it with javascript: the better way would be to go with the element's id, becuase if you change the name of the form everything breaks. This does not happen when you use the id.
I prefer using IDs, as the "function" (i.e.: what you're trying to achieve) of your code isn't tied up with in the semantics. For me, .GetElementById('myid') stands out more, and is more readable that just having "myid" scattered among the code. Plus you can more easily rename elements. That's my 2p worth!

Categories

Resources