tags:

views:

31

answers:

4

I am trying to find out what div is the span is in using jquery.

here is a eg.

 <div id='one'></div>
 <div id='two'></div>
 <div id='three'><span id="find_me"></span></div>

thanks

A: 

$('#find_me').parent() should do the trick.

jwiscarson
@jwiscarson, you should use the code button to format your code for better readability. (*i did it for you in this case*)
Gaby
Understood. Apologies for any inconvenience.
jwiscarson
+1  A: 

alert ( $("#find_me").parent().attr("id") ); // <- three

galambalazs
+1 I think this is the only answer that considers the *actual* question being asked. Sure `.parent()` can break with changes to HTML structure, but that's true for `.parents()` and `.closest()` as well.
patrick dw
+1  A: 

This will get the id of the <div> parent of the <span> with the id find_me:

$("#find_me").parents("div").attr("id")
Adam
Not a big deal, but it usually doesn't make sense to specify a tag name with an ID, since there should only be one of any given ID on the page. It just slows down the selector a little bit.
patrick dw
i think using parent(s) (**with the s**) would be the ideal solution for general use (*since the OP is asking for the div that contains the span*) (*not needed in the specific example though..*) **closest** as @lonesomeday says would be the ideal solution..
Gaby
@Gaby Good point. I didn't know about parents. I've changed it.
Adam
@patrick dw - True. Although what happens if you did specify the id more than once? Then what happen?
Adam
@Adam Things break ;-)
lonesomeday
Adam - @lonesomeday is right. A selector using `#` to find the element will likely only return the first match.
patrick dw
+5  A: 

Use .closest() to find the closest ancestor div (.parent() will only find it it if the div is the immediate parent).

$('#find_me').closest('div').attr('id')
lonesomeday
+1 Closest is the most reliable way to do this with the designers constantly changing the HTML structure and positioning of elements.
James
Of course if you're going to take it beyond the code example, you should then consider that there could be an intermediate `<div>` with no ID attribute, which would mean you would probably want something like `.closest('div[id]')`.
patrick dw
@patrick Well, you might want to do something that doesn't involve finding the id, but yes, nice example :-)
lonesomeday
@patrick, technically the OP is asking for the container `div`, not the one with an id ..
Gaby
@Gaby - Fair enough, but technically, the code in the question shows no ancestors between the `<span>` and the `<div>` with the ID. ;o)
patrick dw
@patrick, true .. it depends on the specs :)
Gaby
http://api.jquery.com/has-attribute-selector/
Peter Ajtai