简体   繁体   中英

Getting class or ID name of an element based on the value of a particular attribute

Is there any way to get the class or ID name of all elements that has a particular value for an attribute? For example if I have the following:

<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>

I want to get the class names of all rectangles where the attribute selected has a value of 1, in this case rect3 and rect5 would be returned.

You can use .map() & attribute equals selector

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM