Een jQuery hasAttr () Equivalent - CSS-trucs

Anonim

jQuery heeft niet echt een .hasAttr()functie. Je zou kunnen aannemen van wel, maar helaas niet.

Een StackOverflow-thread heeft een aantal redelijk goede oplossingen.

Verkrijg het attribuut, controleer de waarde

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 heeft een manier

Als je alleen een jQuery-referentie hebt ...

$(this)(0).hasAttribute("name"); jQObject(0).hasAttribute("name");

Filter de selectie

$(this).is('(name)'); $(this).filter("(name='choice')");