css怎么判断span没有自定义属性没有怎么判断
要判断一个<span>元素是否具有自定义属性,可以使用hasAttribute()方法。该方法接受一个属性名作为参数,如果元素具有该属性,则返回true;否则返回false。
以下是一个示例代码:
<span id="mySpan" data-custom="true">This is a span element with a custom attribute.</span>
<span id="mySpan2">This is a span element without any custom attribute.</span>
<script>
var span1 = document.getElementById("mySpan");
var span2 = document.getElementById("mySpan2");
if (span1.hasAttribute("data-custom")) {
console.log("span1 has a custom attribute");
} else {
console.log("span1 does not have a custom attribute");
}
if (span2.hasAttribute("data-custom")) {
console.log("span2 has a custom attribute");
} else {
console.log("span2 does not have a custom attribute");
}
</script>
输出结果:
span1 has a custom attribute
span2 does not have a custom attribute
如果要判断一个<span>元素是否没有任何自定义属性,可以使用attributes属性和length属性。attributes属性返回一个元素的所有属性节点的集合,length属性返回该集合的长度。如果length为0,则表示该元素没有任何属性。
以下是一个示例代码:
<span id="mySpan">This is a span element without any custom attribute.</span>
<script>
var span = document.getElementById("mySpan");
if (span.attributes.length === 0) {
console.log("span does not have any attribute");
} else {
console.log("span has at least one attribute");
}
</script>
输出结果:
span does not have any attribute
原文地址: https://www.cveoy.top/t/topic/i4yZ 著作权归作者所有。请勿转载和采集!