Best way to manipulate dom element attributes with javascript/jQuery - javascript

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
}
}

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

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

Set variable to HTML elements with certain class?

I'm sure there is a way to set a JavaScript variable to any HTML element with a certain class attached to it? I'm just not sure how to write it. Can anyone help me out?
The best way would be to use a framework, such as jquery, that makes an easy use of (css) selectors, e.g, to select all elements with class my-class do
$('.my-class')
and then apply any code to the list of those elements
edit: don't forget to use the $(document).ready wrapper
you could simply go var x = document.getElementById('somediv'); for example. Now whatever style class pertains to somediv will of course still obtain unless you change it programatically in your javascript.
Hope that helps -- might be able to be more helpful if you give a broader context of what you are trying to accomplish.
To do this without document.getElementsByClassName('myclass') nor $(.'myclass') would be difficult and require some advanced tactics. You would have to recursively generate a list of all DOM objects from the document. While generating the list, every element touched would have to be tested for .className = 'myclass'. This is essentially what jquery does behind the scenes, although I believe on page load it caches the whole DOM for easier querying.

A convention for indicating whether an HTML element is referenced from JS code

This is a follow-up question for In jQuery is it a bad idea to use name=X for all selectors?
I am using Backbone and decided that I wanted a way to differentiate between HTML elements that were bound and those that were not.
So I would write (in HAML):
.container
.title(name='title')
.separator
As you can see it's clear that the dynamic element is title.
The reason for this was so I could mess around with the style and rename classes without worrying about breaking the app. It also means in the template I can tell what the dynamic elements are without needing to go back and forth with the Backbone View.
My question now is, without using the [name] selector, does anyone have a code convention to keep track of which HTML elements are referenced from JS.
I have considering:
Using a common prefix on class names (e.g. class=bind-title)
Using some sort of custom HTML element (
Thanks!
FYI: I'm using CoffeeScript, Backbone and haml_coffee templates.
Updated jsperf to test all suggestions:
http://jsperf.com/class-or-name-attr-lookup/3
I would consider using a class to indicate that it is dynamic.
I'm not sure if you are aware of this but you can have multiple classes on one element. Like so:
.container
.dynamic.title(name='title')
.separator
This works in traditional HAML but I have not tried it with haml-coffee. If it doesn't work, you might have to specify the class like .title{:class => "dynamic"}(name='title').
I prefer this over a prefix on the class name because it's more semantically meaningful, which is how HTML should be used.
I am using data-view attribute on elements being set when rendering my Views.
This helps me to then show a tooltip in a browser window when I hover over View(s).

Categories

Resources