Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
312 views
in Technique[技术] by (71.8m points)

javascript - 使用jQuery获取元素的类列表(Get class list for element with jQuery)

Is there a way in jQuery to loop through or assign to an array all of the classes that are assigned to an element?(jQuery中是否有一种方法可以循环或将分配给元素的所有类分配给数组?)

ex.(例如) <div class="Lorem ipsum dolor_spec sit amet">Hello World!</div> I will be looking for a "special" class as in "dolor_spec" above.(我将在上面的“ dolor_spec”中寻找“特殊”类。) I know that I could use hasClass() but the actual class name may not necessarily be known at the time.(我知道我可以使用hasClass(),但是实际的类名可能在那时不一定是已知的。)   ask by Buggabill translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use document.getElementById('divId').className.split(/\s+/);(您可以使用document.getElementById('divId').className.split(/\s+/);)

to get you an array of class names.(给你一个类名数组。) Then you can iterate and find the one you want.(然后,您可以迭代并找到所需的那个。) var classList = document.getElementById('divId').className.split(/s+/); for (var i = 0; i < classList.length; i++) { if (classList[i] === 'someClass') { //do something } } jQuery does not really help you here...(jQuery并没有真正帮助您...) var classList = $('#divId').attr('class').split(/s+/); $.each(classList, function(index, item) { if (item === 'someClass') { //do something } });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...