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

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.

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.

Giving my Hyperlinks custom attributes

I would like to give all of my URL's attributes. There are probably about 400 on each page. Sometimes only 40, just depending on which type of product is being viewed.
I would like something like this:
Stainless Steel Bolts
How can this be done?
I know that in HTML5 there is some kind of data thing, but I can't find it yet, so maybe I misread something somewhere.
Basically, when any one of those links are clicked, I will (PHP) insert that product into their shopping cart in the database. But, based on the attributes of any given link, I may need to do some calculations/adjustments/etc before I insert them into the DB.
And this seems like the only simple, logical (and somewhat fun) way to go about doing this. But I'm not sure about compatibility between browsers, or whether it's even valid or not.
You're right, it's the data- attribute you're looking for. [random reference]
Your link would look something like this:
<a data-partno="DBF-XJ3" data-qtyType="Box QTY" data-quantity="50">
Demo here: http://jsfiddle.net/wesley_murch/ey2pg/
It's really just a javascript hook, and since jQuery seems to handle it well in all browsers I checked (including IE6), I would say its "safe" to use. As far as I know, you can even make up attributes and it will work with jQuery (although it's not recommended). This is really the best way to avoid abusing rel and title and such (as a lot of people do), just for javascript interaction.
However: I would highly suggest using a <form> with hidden <input>s (and a <button> for easy styling) to submit the values. The other way is broken without javascript, you can enhance it with jQuery afterwards.
You'd do it like this:
$(document).ready(function(){
$("a[href]").each(function(){
if($(this).attr("href") == "link.html"){ //I put a condition here just in case you need one
$(this).attr({
"partno": "DBF-XJ3",
"qtyType": "Box QTY",
"quantity": "50"
});
}
});
});
If all your links need the same attributes, you can remove the condition.
Hope this helps. Cheers
PS: It will work in every browser, however HTML5 recommends to prepend the 'data-' prefix to your custom attributes. Example data-partno="DBF-XJ3"

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

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

__defineSetter__ on innerHTML stops it from rendering

i'm trying to create a watch method for HTML elements, using __define[GS]etter__ when a property is changed. It reacts just fine when i set the value, but if the property listened to, is innerHTML, it somehow fails to render the given string. So basically, when im adding something to innerHTML it doesn't show.
Im using the watch method described in this previous question:
Watch for object properties changes in JavaScript
I could of cause just not listen to innerHTML changes, but i'm also wondering if the __defineSetter__ somehow prevents original handling of setting the value.
Thanks!
That shim code doesn't actually write-through: when you set a property, the value is only remembered on the watch-wrapper and not passed down to the underlying object. It's designed for pure JavaScript objects whose properties have no side-effects (like changing the DOM, in innerHTML's case).
Making it write-through would be a pain since there's no way to directly call the prototype's setter. You'd have to temporarily remove the property, write to the underlying property, then put it back in place.
However it's not really worth pursuing IMO. DOM Nodes are permitted to be ‘host objects’, so there is no guarantee any of the native-JavaScript object-property functions will work on them at all.
(In any case, adding new members onto the Object prototype is generally considered a Really Bad Idea.)
I could of cause just not listen to innerHTML changes
I think that's best, yes.
Ok update.
I found this page on MSDN, which has exactly what i need:
http://msdn.microsoft.com/en-us/library/dd229916(VS.85).aspx
But the Object.getOwnPropertyDescriptor way of doing things apparently only works in IE. Bummer. Any ideas would be appreciated.
I found another webpage with something that looked interesting, but i couldn't quite get it to do what i wanted:
http://www.refactory.org/s/recent/tag/accessors
I've decided to find a workaround for now, something with a timer that checks the attribute for changes and attribute change evnets for browsers that support that.
But if any one finds a solution for the question plz post :)

Categories

Resources