hasAttribute("id") replacement before IE8 - javascript

I have used
element.hasAttribute('id')
in my code to test whether the element has an attribute id. But hasAttribute API is only compatible with browsers after IE8.Is there a similar API or technique which I can use to check the availability of an attribute for an element in my case "id".

In the absence of the hasAttribute method, you need to use getAttribute. This should return null if there is no attribute set, and an empty string otherwise. In practice, some browsers return an empty string, so there's no way in these browsers of telling whether it is an empty attribute or no attribute at all.
if ((element.getAttribute('id') === null) || (element.getAttribute('id') === '')) {

Just check element.id - it'll be an empty string if it's not set.
There's no need to use element.hasAttribute for those attributes that are mirrored by JS object properties.

Related

javascript attr type IE9

For some reason IE9 returns "text" when writing the following code
Any ideas why. Other browsers return email
HTML
<input type="email">
javascript
alert($(input).attr('type'))
That is because IE9 does not support email, thus it ignores the values and resets it to the default value it supports... text.
For some reason IE9 returns "text" when writing the following code Any
ideas why. Other browsers return email
HTML
In a browser that is conformant with W3C standards (where element is a reference to the input element), then:
// Get the value of the HTML type attribute
element.getAttribute('type') // email
// Get the value of the DOM type property
element.type // email or text, depending on whether
// type email is supported or not
getAttribute returns the literal value of the associated attribute. The DOM property returns the actual value that the DOM property is set to (they may be, and often are, different values). IE 9 conforms to the standard—it doesn't support email so the DOM property returns "text", while getAttribute returns "email".
javascript
alert($(input).attr('type')) // email in jQuery version 1.6 and higher
alert($(input).prop('type')) // text in jQuery version 1.6 and higher
According to jQuery documentation, the attr method returns the attribute value, and it does in version 1.6 and higher. To get the DOM property, use prop. Prior to that, jQuery authors tried to second guess what developers actually wanted and attr returned either the attribute or DOM property value based on some unexplained logic.

jQuery and HTML5 valueless (data) attributes

I have data attributes I'm using for options on a table, for example:
<table data-do-something-neat>
...
</table>
I'm using HAML to define them:
%table{ data: { do_something_neat: true } }
...
In HAML it's an HTML5 formatted page, so it's behavior is to drop the value if it's a boolean and true. If it were set to false, it would be gone, like so:
<table>
...
</table>
All this seems fine, but accessing whether that flag is true or false in jQuery is a bit of a pain, and I can't find any definitive reference on how to do it.
For the first table, the following is true:
table.is('[data-do-something-neat]') # true
table.attr('data-do-something-neat') # '' (empty string)
table.data('do-something-neat') # '' (empty string)
And for the second table:
table.is('[data-do-something-neat]') # false
table.attr('data-do-something-neat') # undefined
table.data('do-something-neat') # undefined
So attr and data return something falsy for a true HTML5 data attribute. Is this expected? Is there another data method that could be used? Or am I stuck using is in this way? It's unfortunate to have to use a special method for boolean attributes, instead of just using data for all data attributes.
It kind of makes sense that you're stuck using .is(). Some data attributes should be treated as Booleans, and some should be treated as strings.
Imagine if attr() returned true for an empty string; it would be difficult to test for, and in order to have it properly appear as 'null', your server code would need to write:
<table
<?php if $accountId != null {?>
data-accountId="<?php echo $accountId; ?>"
<?php } ?> >
(The emphasis being on the outside null-checking condition). But, since it returns an empty string, you can simply use javascript and use any standard "is empty string" method you prefer, or just check "if length == 0" if you know the attribute should always be printed from the server.
The difference is that if the attribute is not there, $.attr and $.data return undefined, if it's there without a value, it returns an empty string, which is the expected behavior, as far as I know.
What is the problem with checking?
if (typeof table.attr('data-do-something-neat') !== 'undefined') {
// attribute exists, but it could be the empty string
}
If you want a more straight forward way to test it, you can use Element.hasAttribute
if (table[0].hasAttribute('data-do-something-neat')) {
// attribute exists, but it could be the empty string
}
I would just use a selector and check for the existance of a correctly selected element:
$('table[data-do-something-neat]').length !== 0
or
$('#A').attr('myattr') !== undefined // If attribute exists
That's what's noted in this SO question: Select elements by attribute
Or if you can go without jQuery there are native DOM methods that will suffice:
Element.hasAttribute('data-do-something-neat');

How to select spans that have a specific attribute in javascript

I'm trying to manipulate spans that have the "email" attribute, this is my code:
var spans = document.getElementsByTagName("span"),
index, node, emailAttr;
for (index = 0; index < spans.length; ++index) {
node = spans.item(index);
emailAttr = node.getAttribute("email");
if (emailAttr) {
// Do something with `node` and `emailAttr`
}
}
Everything goes well until the last if statement, it can find the spans but no result for spans that have the email attribute. What is wrong here?
This is part of the html code i'm trying to scan:
<span class="yP" email="nobody#mozilla.org">Mozilla Add-ons</span>
Note: i don't want to use jQuery.
There is no "email attribute". In HTML5, input elements can have an email type. However, HTML5 is not a standard, is not fully supported by any browser and most older browsers only support that part of it that is compatible with HTML 4.01 (which is the current HTML standard).
If you wish to be compliant with HTML5, then non-standard attributes should use a data- prefix so you should be using data-email.
To determine if an element has a particular attribute or not (as opposed to whether the attribute has a truthy value or not), you can consider the hasAttribute method. However, some browsers (e.g. IE < 9) don't support it and there is no viable work around (some have tried by parsing an element's outerHTML but I wouldn't suggest it). Also, you must use getAttribute to read the value because earlier versions of Firefox (and other browsers) do not create element properties for non-standard attributes.
One option for wider support is use a data-email attribute that always has a truthy value (i.e. anything other than an empty string). That way you can test with getAttribute.
An alternative is to use a class so that any element that should have the attribute also has the class, e.g.
<span class="... email ..." data-email="foo#bar.com">foo</span>

select by id in jquery

as all you know
$("#ID")
returns the element having ID.
but this code always return even there's no element.
alert($("#htrBuyerCouponNotice"));
alert(document.getElementById("htrBuyerConponNotice"));
in this case.
those two line results are diffrent.
I want to check whether there is an element has htrBuyerCouponNotice.
document.getElementByID return null if there's no element.
You can check the length property of the jQuery object to determine the number of matched elements, e.g.:
alert($(selector).length);
You can use it directly on if statements e.g.:
var $el = $(selector);
if ($el.length) { // only 0 will coerce to false
// ...
}
But most of the time you don't really need to know if the selector matched elements or not, because the jQuery built-in methods will be simply ignored, e.g.:
$('#nonExistent').hide();
The above statement will not cause any error even if the element was not found.
jQuery has also the size method, but I would recommend you to use the length property directly since it's publicly accessible, the size method is slightly slower since it is only a function that returns the value of length property.
because jQuery returns a list of selected elements, if there are no elements, you still get a return - its just a empty list.
check for $('#someID').length - should work if i remember corretly
When selecting elements, jQuery will always return an array of matching elements. In your case, $('#htrBuyerCouponNotice') is probably returning an empty array. Instead, check $('#htrBuyerCouponNotice').length.
Andrew
Try:
$("#htrBuyerCouponNotice").size()
It'll be zero if there's no nodes with that identifier, 1 if there is.

jQuery 1.3 - Issue with Setting an Attribute Value

This is my first stackoverflow question, so try to be nice. ;-D
My issue is this, I am refactoring some existing javascript code and using jQuery to do it. In several places I've come across javascript code similar to the following:
// some js code working with the customAttribute value
javascriptElementObject.customAttribue = void(0);
The javascriptElementObject is now a jQuery object and I have been attempting to use the following code to do the same thing:
// some js code working with the customAttribute value
javascriptElementObject.attr("customAttribute", void(0));
However, this does not seem to be doing anything. The following code works however:
javascriptElementObject.get(0).customAttribute = void(0);
I'm aware of jQuery's removeAttr() function, but have not used it so far because I don't know if it's equivalent to setting the attribute value to void(0).
So I guess that really means I have 2 questions:
Why doesn't the first jQuery version work?
Are .get(0).customAttribue = void(0); and .removeAttr("customAttribute); equivalent?
Thanks.
jQuery likes to overload its methods so:
obj.attr( name ) //retrieves the attribute value
obj.attr( name, value ) //sets the attribute
obj.attr( name, void(0) ) == obj.attr( name, null ) == obj.attr( name ) //i.e retrieving the attribute
You might want to try the following if you want to set an empty attribute
obj.attr( name, '' )
This will also apply to other methods jQuery.html() for example
What are you trying to accomplish?
If the goal is to remove the value in the name/value pair, you might as well just remove the attribute entirely. I'm not aware of any intrinsic value in maintaining an attribute that has no value; in less standards-compliant browsers it may even cause a problem.
In general, the syntax of $(selector).attr(name, value) and $(selector).removeAttr(name) work very well (at least I've never seen it fail.)
If you're trying to use void(0) to keep A HREFs from firing you'd be better off using a "return false" as the click event on those A tags.
The only way to work with custom attributes via jQuery objects is:
obj.get(0).myCustomAttr = 'some value';
That is because jQuery's attr() method will not work with custom attributes (except while applied on a XML-document).
Note also that meouw's answer regarding jQuery overloading functions is not precisely correct, because jQuery checks for the parameters passed to it in such a manner that:
jQuery.funcname(param)
and
jQuery.funcname(param, null)
differ, becacuse null !== undefined. For example:
var params_test = function(a) {
if (a === undefined) {
return 'called with no parameters';
} else {
return 'called with one parameter: ' + a;
}
};
params_test(); // results in 'called with no parameters'
params_test(null); // results in 'called with one parameter: null'
Uhmm, try this:
javascriptElementObject.attr("customAttribute", void(0));
var _void = javascriptElementObject.attr("customAttribute");
alert(_void);

Categories

Resources