jquery - 如何检查元素是否附加了任何类

Pet*_*ter 1 jquery

你会想象这很容易实现,但是很好..

无论如何,我有一个元素,根据网站上的交互添加或删除类.

我可以轻松地检查对象是否具有特定的类 $(element).hasClass("myClass")

但是如何在不知道其名称的情况下检查元素是否附加了任何类.就像是:

$("#mydiv").hasAtLeastOneClassPresent
{
 do this
}
$("#mydiv").hasNotASingleClass
{
 do that
}
Run Code Online (Sandbox Code Playgroud)

Dav*_*mas 8

检查classList财产:

$("#mydiv").prop('classList').length
Run Code Online (Sandbox Code Playgroud)

或者,使用DOM:

document.querySelector('#mydiv').classList.length
Run Code Online (Sandbox Code Playgroud)

如果长度为零,则它没有类,如果它大于零,则它具有该类数.

以DOM为功能:

// a named function to take a DOM node:
function hasClasses(node) {

  // returns a Boolean, true if the length
  // of the Array-like Element.classList is
  // greater than 0, false otherwise:
  return node.classList.length > 0;
}

var elem = document.getElementById('mydiv');

if (hasClasses(elem)) {
  elem.classList.add('found');
}
Run Code Online (Sandbox Code Playgroud)

function hasClasses(node) {
  return node.classList.length > 0;
}

var elem1 = document.getElementById('mydiv'),
  elem2 = document.getElementById('myotherdiv');

if (hasClasses(elem1)) {
  elem1.classList.add('found');
}

if (hasClasses(elem2)) {
  elem2.classList.add('found');
}
Run Code Online (Sandbox Code Playgroud)
div {
  height: 2em;
  border: 3px solid limegreen;
  margin-top: 0.5em;
  border-radius: 1em 0;
}
.found {
  border-color: orange;
}
Run Code Online (Sandbox Code Playgroud)
<div id="mydiv" class="hasAClass"></div>
<div id="myotherdiv"></div>
Run Code Online (Sandbox Code Playgroud)

JS小提琴演示.

如果浏览器没有element.classList界面功能,您可以使用className:

// retrieving the specified element,
// retrieving its 'className' property,
// removing the leading and trailing white-space,
// retrieving the length of the trimmed string,
// checking that this length is greater than 0:
$("#mydiv").prop('className').trim().length > 0;
Run Code Online (Sandbox Code Playgroud)

var div1 = $("#mydiv"),
  div2 = $('#myotherdiv'),
  div1HasClassName = div1.prop('className').trim().length > 0,
  div2HasClassName = div2.prop('className').trim().length > 0;

// Boolean true:
if (div1HasClassName) {
  div1.addClass('found');
}

// Boolean false:
if (div2HasClassName.length > 0) {
  div2.addClass('found');
}
Run Code Online (Sandbox Code Playgroud)
div {
  height: 2em;
  border: 3px solid limegreen;
  margin-top: 0.5em;
  border-radius: 1em 0;
}
.found {
  border-color: orange;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mydiv" class="a"></div>
<div id="myotherdiv"></div>
Run Code Online (Sandbox Code Playgroud)

JS小提琴演示.

或者,使用DOM:

// retrieving the element with the id of 'mydiv'
// (or null if no such element exists),
// retrieving the className, as a String, of the element,
// removing the leading and trailing white-space,
// retrieving the length of the String,
// evaluating whether the length is greater than 0;
// returning a Boolean true if so, false if not:
document.querySelector("#mydiv").className.trim().length > 0;
Run Code Online (Sandbox Code Playgroud)

var div1 = document.querySelector("#mydiv"),
  div2 = document.querySelector('#myotherdiv'),
  div1HasClassName = div1.className.trim().length > 0,
  div2HasClassName = div2.className.trim().length > 0;

// Boolean true:
if (div1HasClassName) {
  div1.className += ' found';
}

// Boolean false:
if (div2HasClassName) {
  div2.className += ' found';
}
Run Code Online (Sandbox Code Playgroud)
div {
  height: 2em;
  border: 3px solid limegreen;
  margin-top: 0.5em;
  border-radius: 1em 0;
}
.found {
  border-color: orange;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mydiv" class="a"></div>
<div id="myotherdiv"></div>
Run Code Online (Sandbox Code Playgroud)

JS小提琴演示.

也可以编写一个(非常)简单的jQuery选择器来只选择那些有类的元素,这个选择器不带参数:

// defining the selector-name 'hasClasses':
$.expr[':'].hasClasses = function(

  // this is the current element of the collection over
  // which the selector iterates:
  objNode
) {

  // here we return true, if:
  //   the current node has a 'class' attribute, and
  //   has a classList (though this could be substituted
  //   for className for backwards compatibility), and
  //   the classList.length is greater than zero
  // Otherwise returning false:
  return objNode.hasAttribute('class') && objNode.classList && objNode.classList.length > 0;
};


$('div:hasClasses').addClass('found');
Run Code Online (Sandbox Code Playgroud)

$.expr[':'].hasClasses = function(
  objNode
) {
  return objNode.hasAttribute('class') && objNode.classList && objNode.classList.length > 0;
};


$('div:hasClasses').addClass('found');
Run Code Online (Sandbox Code Playgroud)
div {
  height: 2em;
  border: 3px solid limegreen;
  margin-top: 0.5em;
  border-radius: 1em 0;
}
.found {
  border-color: orange;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class></div>
<div class="hasAClass"></div>
<div class=""></div>
<div></div>
<div class="hasAClass"></div>
Run Code Online (Sandbox Code Playgroud)

JS小提琴演示.

或者,类似地,一个jQuery插件也不带参数:

// using an immediately-invoked function expression (IIFE),
// to immediately run the function as soon as it's encountered:
(function($) {

  // defining the plugin name ('hasClasses'):
  $.fn.hasClasses = function() {

    // 'this', here, is the jQuery collection
    // over which we're iterating with filter():
    return this.filter(function() {

      // we're using this node potentially three times,
      // so we cache it here for simplicity ('this,' within
      // the filter() method, is the DOM node):
      var objNode = this;

      // if the following assessment returns true the
      // current node is retained in the collection and
      // and retained for chaining, if it evaluates to
      // false it's discarded from the collection and so
      // not retained/returned:
      return objNode.hasAttribute('class') && objNode.classList && objNode.classList.length > 0;
    });
  };

// passing in jQuery to allow the use of the $ alias
// within the IIFE:
})(jQuery);

// calling the plugin:
$('div').hasClasses().addClass('found');
Run Code Online (Sandbox Code Playgroud)

(function($) {
  $.fn.hasClasses = function() {
    return this.filter(function() {
      var objNode = this;
      return objNode.hasAttribute('class') && objNode.classList && objNode.classList.length > 0;
    });
  };
})(jQuery);

$('div').hasClasses().addClass('found');
Run Code Online (Sandbox Code Playgroud)
div {
  height: 2em;
  border: 3px solid limegreen;
  margin-top: 0.5em;
  border-radius: 1em 0;
}
.found {
  border-color: orange;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class></div>
<div class="hasAClass"></div>
<div class=""></div>
<div></div>
<div class="hasAClass"></div>
Run Code Online (Sandbox Code Playgroud)

JS小提琴演示.