简体   繁体   中英

Find element by css value jQuery

I have a div that changes a lot and I need to do find a child element that has the same value and store its id.

Goal: Find span with the same left attr as div.stuff, return the span id (In this case the id returned in the alert should be 3)

HTML

<div class="stuff" style="left:100px">
    <span id="1" style="left:0"></span>
    <span id="2" style="left:50px"></span>
    <span id="3" style="left:100px"></span>
    <span id="4" style="left:150px"></span>
</div>

jQuery

var stuff = $('.stuff').css('left');
var id = $('.stuff').find('span[left=100px]').attr('id');

alert(id);

Fiddle http://jsfiddle.net/56TWg/

You can use filter() here:

var id = $('.stuff span').filter(function () { 
    return $(this).css('left') == '100px' 
}).attr('id');

Updated Fiddle

Here's a snippet that achieves that:

var leftValue = $('.stuff').css('left');
alert(leftValue);

var id = $('.stuff').find('span[style*="left:' + leftValue + '"]').attr('id');

alert(id);

fiddle: http://jsfiddle.net/d8SHd/

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