jQuery doesn’t really have an .hasAttr()
function. You might assume that it does, but alas, it does not.
A StackOverflow thread has some pretty good solutions.
Get the attribute, check the value
var attr = $(this).attr('name');
// For some browsers, `attr` is undefined; for others, `attr` is false. Check for both.
if (typeof attr !== typeof undefined && attr !== false) {
// Element has this attribute
}
Native JavaScript has a way
If you only have a jQuery reference…
$(this)[0].hasAttribute("name");
jQObject[0].hasAttribute("name");
Filter the selection
$(this).is('[name]');
$(this).filter("[name='choice']");
Looks like an extra typeof is in if condition of first code block. Shouldn’t it be : if(typeof attr !== ‘undefined’ && attr !== false) … ?
The first typeof applies to the attr, the second typeof applies to undefined. But more importantly, I was wondering if it could be shortened to:
var attr = $(this).attr(‘name’);
// For some browsers,
attr
is undefined; for others,attr
is false. Check for both.if (attr && attr !== false) {
// Element has this attribute
}
or
if (attr) {
// Element has this attribute
}
I think testing for if (attr) would identify whether attr was undefined would it not?
Tim
Not sure if I’m missing something, but what about this?
if ($(this).is('[name]')) {
// Element has this attribute
}
Hello. If you don’t put “undefined” in quotes it doesn’t work for Chrome.
You should use or ( || ) argument instead of && because it is not working here is the correct form.