What is the preferred method of retrieving class names with jQuery? - javascript

So far, I'm using
$(this).attr('class');
But I worry about compatibility because I know some browsers do some weird things with class and id attributes. Seems like a great place for jQuery to implement its own method, but I can't find it in the documentation.
Isn't there a bug somewhere that has className and id acting on the same objects? This may only apply to IE setting values, or maybe I'm just misremembering.
As meder pointed out, I was thinking of id and name, not id and class.

.attr('class') would work out because internally it uses className

Related

document.formname.checkbox[0].checked versus document.getElementById('checkbox').checked

In Javascript, I usually use the syntaxdocument.formname.checkbox[0].checked, but I notice that almost everyone else uses document.getElementById('checkboxid').checked. My apologies if this seems a silly question, but I'm trying to find out if my preferred syntax has been deprecated, or do others simply use what is more convenient?
What each means:
document.formname.checkbox[0].checked
This uses the form's and the element's name= attribute to select the element you want. It's good because sometimes you don't want to dirty your markup with IDs everywhere, and you'd prefer to use names, which are something most forms has (because default submission uses names as keys).
The potential problems with that is that it's a bit verbose, and might not very readable.
document.getElementById('checkboxId').checked
This has the simplicity of just plugging an ID and getting the correct element, but then to get any element in the form, it must also have an ID, which can be pretty annoying.
document.querySelectorAll('#myForm input[type=checkbox]')[0].checked
Here's an alternative solution, which uses CSS selectors and document.querySelectorAll(), I feel that it's more readable, especially for people who are more proficient in CSS than in JavaScript.
Which of those is better? Depends on your particular use case and preference. I like to use querySelector and querySelectorAll, especially if I already have the form DOM object in a variable:
myForm.querySelector('input[type=checkbox]').checked;
It's up to you.
getElementById is preferred. Consider a webpage with the following contents:
<div id="x"></div>
You can access your div x in javascript with just console.log(x).
Now consider if you had var x = 5 defined in the global context. Well, now you can't use x to access your div before it now has a value of just 5.
getElementById is preferred because you don't have the potential to overwrite your selector with a variable for something else.
document.formname.checkbox[0].checked might not actually work on all Browsers. document.forms[0].elements and document.formName is standardized, as is document.getElementById()

removing and adding attributes for the second time not working in IE

In Internet Explorer, the following code doesn't work if its called a second time
$(e.target).siblings().prev().removeAttr("checked");
Please provide all the help you can.
Thank you.
Removing an attribute using javascript will remove the attribute from the element permanently.
You can use $(e.target).siblings().prev().prop("checked", false); instead. This will only update the element instead of permanently altering it.
Without getting too detailed in an already answered question, you can check out this answer on the differences between attr and prop in JQuery. Notably, the checked attribute and property behave in different ways, where the attr potentially reflects the default value while the prop reflects the current value. In most cases (since JQuery 1.6), using .prop() to manipulate element properties is favored.

How is this element accessible when not found with selector

In my company, some of the code accesses html elements purely by id, rather than document.getElementById or jQuery $("#id"). For example, if there is a select with an id of test they then use alert(test.selectedIndex) in the javascript and this works.
This breaks my model of how elements can be found / accessed in the DOM and I would have expected the alert to say that test was undefined. However, this works (and I have set up a fiddle to double check this). Can anyone please explain why elements can be accessed by their id, without any need for a getElementById / jQuery selector?
Many thanks.
See http://www.w3.org/html/wg/drafts/html/master/browsers.html#named-access-on-the-window-object (noting that 'globals' in javascript are just looked up from properties on the window object, so window[id] is exactly the same as just id, if id is not defined as a local variable)
This was previously non-standard behaviour, added by IE, that has now become part of the HTML5 spec.
In general I wouldn't recommend relying on it though because, as you've noticed, it can be quite confusing.

Is it safe to use JQuery event names as class names?

I'm testing a remote site and the click event for an element isn't working in some Windows environments for Internet Explorer and Safari.
I've noticed the class name for elements that are clickable is "click". So the event is defined like this:
$('.click').click(function() {
Before I delve deeper into other possible causes, does this look safe?
Thanks
Sean
Absolutely, jQuery/Javascript event names are totally unrelated to CSS class names until the two are paired by a developer (or a framework, however in such instances the classes are typically prefixed).
With that in mind, you may want actually to move away from using such generic 'event-centric' class names, CSS after all is 'style centric', if you are identifying clickable elements, you could instead give them the attribute data-clickable='true' and change your selector to $('[data-clickable=true]'). By doing so you maintain the distinct seperation between style (CSS), content(HTML) and function (JS) deemed to be best practice. That said, to go back to your question, it really doesnt matter in the way you ask.
Of course it does look safe and is safe. There is no harm in using event names as class names, until you don't get confused ;)
Both are different. CSS cannot conflict with JS. So, it is safe to use what you're using.

$(element).data("dataAtribute") vs $(element).hasClass("className")

Which is quicker in jQuery?
$(element).data("dataAtribute");
or
$(element).hasClass("className");
My first guess was .hasClass since it doesn't have to work with custom attributes, but checks the native .className attribute.
According to this test I am right. But didn't think it would be THAT much (~90%) of a difference though.
Checking these methods in the source (see src/data.js and src/attributes.js) makes it quite clear.
Try it and see - especially as this is so simple. Please report back with your findings too.
I would guess that data() is quicker as it's directly checking an attribute, as opposed to having to search the class attribute for a value.

Categories

Resources