javascript - 根据特定属性的值获取元素的类或 ID 名称

标签 javascript jquery html

有没有办法获取具有特定属性值的所有元素的类或 ID 名称?例如,如果我有以下内容:

<rect class="rect0" x="45" y="0px" width="40px" height="40px" fill="#ff0000" selected="0"></rect>
<rect class="rect1" x="90" y="0px" width="40px" height="40px" fill="#ff0000" selected="0"></rect>
<rect class="rect2" x="135" y="0px" width="40px" height="40px" fill="#ff0000" selected="0"></rect>
<rect class="rect3" x="180" y="0px" width="40px" height="40px" fill="#0400fb" selected="1"></rect>
<rect class="rect4" x="225" y="0px" width="40px" height="40px" fill="#ff0000" selected="0"></rect>
<rect class="rect5" x="270" y="0px" width="40px" height="40px" fill="#0400fb" selected="1"></rect>
<rect class="rect6" x="315" y="0px" width="40px" height="40px" fill="#fb0004" selected="0"></rect>

我想获取所选属性值为 1 的所有矩形的类名,在本例中将返回 rect3 和 rect5。

最佳答案

您可以使用.map() & attribute equals selector

var array = $('rect[selected="1"]').map(function(){
    return this.className;
}).get();

关于javascript - 根据特定属性的值获取元素的类或 ID 名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22725921/

相关文章:

javascript - 在设备上使用 JavaScript 向 Azure 通知中心注册

javascript - 从 URL 检索的正则表达式

javascript - 加载 jquery-migrate.min.js 时如何摆脱错误 "Unsupported format of the sourcemap"?

html 5 Canvas 阴影只有一个边框

html - Wordpress:在响应式 View 中,容器不会占据全宽

html - 垂直/水平居中伪元素的生成内容

javascript - 尝试在图表上绘制虚线

javascript - $.getJSON 在 for 循环中没有 let 语句以实现浏览器兼容性

javascript - jQuery 选择更改/单击问题 - 更改在 IE 中不起作用,单击在 Chrome 中不起作用

jQuery:我可以遍历 not() 方法吗