Como saber si un elemento posee una determinada clase: is('.class'), hasClass('class'), ver los comentarios
is('.class'), hasClass('class'), ver los comentarios
by limd
HTML
<html>
<head>
<link href='https://fonts.googleapis.com/css?family=Droid+Sans' rel='stylesheet' type='text/css'>
</head>
<body>
<h1>Selecting in jQuery</h1>
<h2><span class="plus">+</span> you can select by a filter as well <b>$(':hidden')</b></h2>
<p>It is not necessary to provide an actual element in conjunction with a filter, such as
$('div:hidden'). It is possible to simply pass the filter alone, anywhere a selector expression is
expected.</p>
<a title="jQuery">jQuery.com</a>
<a href="http://www.jquery.com" title="jQuery" class="foo">jQuery.com</div>
<a href="">jQuery.com</a>
<a href="http://www.jquery.com" title="jQuery">jQuery.com</div>
<div class="work-area">
<div id="i0">jQuery</div>
<div id="i1">jQuery</div>
</div>
</body>
</html>
CSS
body {
line-height: 20px;
padding: 10px;
font-family: 'Droid Sans', sans-serif;
font-size: 13px;
}
h1 {
font-size: 16px;
text-align: center;
margin: 10px;
padding: 10px;
}
h2 {
font-size: 14px;
}
p {
padding-left: 50px;
font-size: 13px;
}
.work-area {
border-left: 3px solid #66a3d2;
padding: 10px;
margin: 10px;
}
.plus {
color: #66a3d2;
font-size: 18px;
}
JavaScript
jQuery(document).ready(function() {
// Returns true
console.log($('div').is('#i1'));
// Returns false. Wrapper set contains no <div> with id="i2"
console.log($('div').is('#i2'));
// Returns false. Wrapper set contains no hidden <div>
console.log($('div').is(':hidden'));
/*Some developers use is('.class') to determine if an element has a specific class, don't forget that jQuery
already has a method for doing this called hasClass('class') which can be used on elements that contain more
than one class value. But truth be told, hasClass() is just a convenient wrapper for the is() method*/
// Alerts "1"
//alert($('a[title="jQuery"][href^="http://"][class!=""]').length);
// Get all checkboxes that are both visible and checked
$(':checkbox:visible:checked')
});