user934902
user934902

Reputation: 1204

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/

Upvotes: 1

Views: 94

Answers (2)

Rui
Rui

Reputation: 4886

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/

Upvotes: 1

Felix
Felix

Reputation: 38102

You can use filter() here:

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

Updated Fiddle

Upvotes: 5

Related Questions