Local id-s for HTML elements - javascript

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"]');

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.

Javascript/HTML: Using id vs. class when naming

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).

xml inside html

What is the issue regarding placing xml elements inside html ? I am trying to easily retrieve javascript event info which returns some html when a div is clicked on. I want to parse that (as I cant send any data object afaik) and its very easy so I'm doing
<div><currency>eur</currency><price>120</price><weight>2kg</weight></div>
and in the js im doing
doTap=function(sent) {
console.log(sent.getElementsByTagName('price')[0].innerHTML);
The issue is that XML is not valid HTML (with respect to the elements). The browser does not know how to render a currency element, and afaik there is no standard way to deal with unknown elements. Some browsers might ignore them completely.
You should be fine with using span elements and giving them a class:
<div>
<span class="currency">eur</span>
<span class="price">120</span><
<span class="weight">2kg</span>
</div>
a elements are not supposed to contain block elements btw.
Then get the element in question by its class.
If you don't want to display the information (currency, price, etc) but only need to store it somewhere, you can use HTML5's data-* attributes:
<a data-currency-"eur" ... ></a>
and access them with getAttribute.
The main practical problem is that IE 8 and older do not deal at all with tags they don’t know when processing HTML documents. To deal with this, you can add code like document.createElement('currency').
There are other issues, too, such as the risk that some future browsers will start recognizing the markup you have invented – and this may cause unpredictable rendering features and functionality. Some more notes: http://www.cs.tut.fi/~jkorpela/pragmatic-html.html8#custom
The safer approach is to use span elements with class. You can also use a elements, since without href, they are still valid but do not create links, making the element effectively just a text-level container. By HTML syntax rules, though, you must not nest a elements (but browsers don’t care, in things like this).
So the safest approach uses e.g. <span class=currency>EUR</span> etc. instead.

Best way to manipulate dom element attributes with javascript/jQuery

I want some return about dom manipulation. I think we can save elements' status in several ways. For exemple, you want to make an element "inserted", what do i have to use? :
Add css class as "inserted"
Save an attribute with .data("inserted",true)
Push my element in a global array containing all "inserted" elements
...
But what is the best way? Maybe the solution is to use all possibilities. I don't know.
That's a general question. I don't have a specific problem, but i am starting developing a huge javascript application and i want to choose my rules :)
Do you want selected elements to look in a specific way?
--> Use the css-class
Do you want to check whether a specific element is selected at a different place in code?
--> Use .data
Do you want to do something to all selected elements?
--> Use an array.
If you plan to do multiple of the things above, you can also combine the approaches.
If you want a visual element to accompany the status, then the CSS class is the obvious way to go.
Data elements are a perfectly valid way of tagging something as well.
If you want to persist state, then saving element status in a JSON structure may be a good option. The JSON data is the "master model" and the elements are rendered based on its model. The JSON data can be passed to the server or to the next page easily.
This is a hard question to answer generally because it really depends on the needs of your application. How many elements do you need to evaluate at any given time? A dozen? A few thousand? What else do you need to do with these elements when you select them? Basic guidelines are:
Don't add a selected class unless you really need to change the style of the element.
If you need to traverse to an element based on whether it has been selected or not, do not use the data() option.
Do not cache the selected elements in memory (variables or localStorage or whatever) if you don't need them to persist for more than one simple call. The overhead of managing your array of selected elements is only worth it if you have a noticeable performance gain or need to persist the data.
So, what do you really need to do with these elements? With more information about your situation, we can make a better recommendation.
For me this depends on what the use of the status will be...
If layout changes depending on selected, i use a class
JS logic (more than only styling) -> atribute
I hardly use classes to add js logic to elements ... css tends to change more often than the underlying javascript files. In case I use classes in js, I force myself to keep the classnames and selectors in css or just redo all element-selection in both js and css when one needs to change (for instance because of using another library or css templates)
as for your third option, an attribute can give you an array of all selected alemens useing a jquery selector $('*[selected]')
if things get complicated I put enhanced dom elements into "classes"
var InserttMe = function(element){
this.element = element;
this.inserted= false;
};
selectMe.prototype = {
insert: function(){
this.inserted= true;
//do whatever you do with your element
}
}

setting value of name for an image in the DOM

I need to set the value of name for my image tag in the DOM. What is the correct property name? More importatnly how do I navigate the DOM, i.e. finding all the different properties and methods with out having to post each time I need one? I tried this search on Mozilla Developer
If, by "name", you mean the title of the image, then it would be the .title attribute on the image.
You navigate the DOM based on what you're trying to find and what identifiers there are in the DOM. You can find things by ID, by class name, by tag type or even by attribute. Which you would use depends upon how your HTML is strucutred, what you're looking for and what identifying information is in the HTML. If you post your HTML and which objects you're trying to locate, we can explain what your options are.
document.getElementById("xxxx") will find any object in the DOM by id.
document.getElementsByTagName("xxxx") will find a list of objects by tag name.
For more advanced methods of finding things, people generally use a selector library (such as Sizzle or what's in jQuery or YUI) that contains much more advanced logic.

Categories

Resources