jQuery-如何检查元素是否具有任何附加的类 [英] jquery - how to check if element has any classes attached to it

查看:50
本文介绍了jQuery-如何检查元素是否具有任何附加的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您会想象这很容易实现,但是哦.

you would imagine this would be easy to implement, but oh well..

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

anyway, I have an element to which classes are added or removed based of interaction on the site.

我可以使用$(element).hasClass("myClass")

但是如何在不知道元素名称的情况下检查元素是否具有任何附加的类.像这样:

but how do I check if the element has any classes attached to it without knowing their names. Something like:

$("#mydiv").hasAtLeastOneClassPresent
{
 do this
}
$("#mydiv").hasNotASingleClass
{
 do that
}

推荐答案

检查classList属性:

$("#mydiv").prop('classList').length

或者,使用DOM:

document.querySelector('#mydiv').classList.length

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

If the length is zero it has no classes, if it's greater than zero it has that number of classes.

以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');
}

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');
}

div {
  height: 2em;
  border: 3px solid limegreen;
  margin-top: 0.5em;
  border-radius: 1em 0;
}
.found {
  border-color: orange;
}

<div id="mydiv" class="hasAClass"></div>
<div id="myotherdiv"></div>

JS小提琴演示.

如果浏览器不具有element.classList界面,则可以改用className:

In the event of a browser that doesn't feature the element.classList interface, you could instead use 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;

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');
}

div {
  height: 2em;
  border: 3px solid limegreen;
  margin-top: 0.5em;
  border-radius: 1em 0;
}
.found {
  border-color: orange;
}

<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>

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;

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';
}

div {
  height: 2em;
  border: 3px solid limegreen;
  margin-top: 0.5em;
  border-radius: 1em 0;
}
.found {
  border-color: orange;
}

<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>

JS小提琴演示.

还可以编写一个(非常)简单的jQuery选择器,以仅选择具有类的那些元素,该选择器采用 no 自变量:

It's also possible to write a (very) simple jQuery selector to select only those elements that have classes, this selector takes no arguments:

// 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');

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


$('div:hasClasses').addClass('found');

div {
  height: 2em;
  border: 3px solid limegreen;
  margin-top: 0.5em;
  border-radius: 1em 0;
}
.found {
  border-color: orange;
}

<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>

JS小提琴演示.

或者类似地,同样不带任何参数的jQuery插件:

Or, similarly, a jQuery plugin that also takes no arguments:

// 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');

(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');

div {
  height: 2em;
  border: 3px solid limegreen;
  margin-top: 0.5em;
  border-radius: 1em 0;
}
.found {
  border-color: orange;
}

<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>

JS小提琴演示.

这篇关于jQuery-如何检查元素是否具有任何附加的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆