我需要从一个元素中获取类名,但我只知道其中一部分。
<div class="anotherclass my-class-no-1 onemoreclass...">div>
我可以以此命名元素
$([class*="my-class-no-"]...
但是如何获得完整的类名?
非常感谢您的解释。
答案 0 :(得分:1)
您可以使用className并搜索包含子字符串的类名称
let subclass = 'my-class-no-';
$('[class*="'+subclass+'"]').each(function() {
let name = this.className.split(' ').find((className) => {
return className.indexOf(subclass) !== -1;
});
console.log(name);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="anotherclass my-class-no-1 onemoreclass">
<div>
答案 1 :(得分:0)
尝试
console.log( $(".anotherclass").attr("class").split(' '));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="anotherclass my-class-no-1 onemoreclass"><div>
答案 2 :(得分:0)
我会做这样的事情: (请参阅网络快照程序中的评论)
var search = "my-class-no-"; // Added to enter the searched class only once
var elms = $("[class*=" + search + "]"); // Get match
var classstr = elms.attr("class"); // Get the class attribute
// Split the string class attribute string to only keep the class that was searched
var myClass = classstr.substring(classstr.indexOf(search)).split(" ")[0];
console.log(myClass);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="anotherclass my-class-no-1 onemoreclass"></div>