根据类别选择DIV ID [英] Select DIV ID based on its class
问题描述
我需要选择并使用DIV的ID,但我不知道它的名称,因此我想搜索我知道的它的类.我该怎么做?我可以使用普通的JS或jQuery,都没关系.
I need to select and use a DIV's ID but I don't know the name of it so I want to search for its class which I know. How would I do that? I can use either plain JS or jQuery, doesn't matter.
我希望能够完全基于其HA
类来获取整个ID.一个示例div看起来像
I want to be able to get the whole ID based purely on its HA
class. A sample div looks like
<div class="HA" id="k2348382383838382133">
我能够使它起作用的唯一方法是,如果我使用一个正则表达式,并且该ID的前几个字符(目前)不会改变(目前),但是将来可能会改变,所以我不会想冒险.
The only way I have been able to get it to work is if I use a regular expression with the first few characters of the ID that I know are not changing (for now) but may in the future so I don't want to risk it.
var selectDivID = $('div[id^="k23"]');
推荐答案
If you know the class, why don’t you just select the element natively using getElementsByClassName
?
var id = document.getElementsByClassName('HA').item(0).id;
当然,您也可以迭代 HTMLCollection
如果还有更多项目(而不是null
).
Of course, you can also iterate the HTMLCollection
if there’s more items (and not null
).
If you have to assert it’s a div
, and if you want to get them all, use querySelectorAll
instead:
var IDs = [];
Array.prototype.forEach.call(document.querySelectorAll('div.HA'),
function(item){ IDs.push(item.id) });
console.log(IDs);
这篇关于根据类别选择DIV ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!