Set variable to HTML elements with certain class? - javascript

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.

Related

Is calling a bunch of HTML in a JS function bad practice?

Here's what I'm trying to do:
I am doing a few things to my text input via "oninput=myFunction()"
When I start typing I wanted to do a few things:
I have the function removing a few elements and adding a textNode already, however, I need it to add 35-40 lines of HTML as well.
Would this be bad to do?
I'm not exactly sure how I should set it up to call this HTML through the function yet.
What's the best/cleanest way to go about doing this?
Should I just keep the HTML wrapped with a hidden display:none class, and have the function add a visible class?
I feel like that wouldn't be the best method, so that's why I'm here asking!
Any advice is appreciated. I'm typing on my phone so sorry if I wasn't very clear.
The better way in my opinion is have a script that will add your event handler after the element is ready (after page load). This function should take care of creating and removing any element that are part of the script on the fly.
Doing this will make sure your HTML is clean and that the JavaScript will do what it is responsible for. There are good ways to create HTML with JavaScript by using methods such as document.createElement and document.createTextNode. When your elements are created, you can append them in the right positions.
To help get the best rendering on all browsers, it is usually a good practice to make your elements display: none before everything is ready to display.

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

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

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

Is using document.getElementsByTagName() a good idea or bad idea?

Ok so I am wondering which way is the preffered way to access a certain tag.
Is it better to use..
document.getElementById('myDiv').innerHTML
or this way..
document.getElementsByTagName('div')[0].innerHTML
// I use [0] because it is the first div in the body
My guess is that it doesn't matter at all which way i do it.
Absolutely the getElementById is better in that case. It's much faster.
Update
Here is a test about JavaScript selector functions. http://jsperf.com/queryselectorall-vs-getelementbyid/6
There are not many articles about performance of JavaScript selector functions. Instead there are many articles about jQuery selector performance like this or this. jQuery uses native JavaScript selector functions internally, so you can guess from these articles.
They do completely different things. If you want to get a particular element and you always need to get the same element, use an id. If you want to get a particular element based on what place it has in the DOM, then use the it's position in the getElementsByTagName NodeList.
If you want to get a particular element and you get it by index, then your script will be brittle - if you change your DOM structure later, you will need to change your code. If you want to get an element by it's position, then using an ID will require you to add redundant attributes to your markup.
Also, it is important to note that getElementById returns a DOM node, while getElementsByTagName returns a NodeList. To quote MDC on the properties of a NodeList:
NodeList is live, meaning that it updates itself automatically to stay in sync with the DOM tree without having to call document.getElementsByTagName again.
So if you need a particular element, getElementById will be significantly faster.
For readability purposes, it depends on what you're trying to do.
Is your intent to get the first div, which just happens to be named myDiv? if yes, then I think getElementsByTagName is better, as it would more express what you're trying to do.
Or is your intent to get myDiv, which just happens to be the first div? If that's the case, then use getElementById.
All other considerations aside, go with the one that expresses your intent.

Categories

Resources