1

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/

2 Answers 2

5

You can use filter() here:

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

Updated Fiddle

Sign up to request clarification or add additional context in comments.

1 Comment

+1 even would be better to filter it using position imho: jsfiddle.net/56TWg/8
1

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/

2 Comments

Worth noting that this only works if the only thing in the style attribute is exactly this. Even so much as a semicolon at the end and this breaks.
@Rui still could be: left: 100px

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.