JS hasAttribute具有数据属性值 [英] JS hasAttribute with data attribute value
本文介绍了JS hasAttribute具有数据属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有jQuery的本机方法来检查dom元素是否具有具有所选值的属性.例如:
Is there a native way, no jQuery, to check if a dom element has the attribute with the selected value. For example:
//assume doc has
data-mod="do" defined
这将是真的:
document.hasAttribute('data-mod');
但这将是错误的:
document.hasAttribute('data-mod="do"')
有没有办法原生检查DOM元素上具有该值的数据属性?
Is there any way to natively check for a data attribute on a DOM element with the value?
推荐答案
You have to access the attribute's value via getAttribute
and compare it to your expected string:
if (node.getAttribute('data-mod') === 'do') {
...
}
对于现代浏览器,您可以使用 matches
:
For modern browsers you can use matches
:
if (node.matches('[data-mod="do"]')) {
...
}
…或对于[data-*]
属性,您可以使用 dataset
:
… or for [data-*]
attributes you can use dataset
:
if (node.dataset.mod === 'do') {
...
}
这篇关于JS hasAttribute具有数据属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文