views:

377

answers:

3

I've read the documentation over and over and I can't get why this doesn't work:

From inside a function, calling the following:

alert($(this).parent().parent().html());

returns something looking like this:

<div class="something1">
    <div class="whereThisStarted">stuff</div>
    </div>
<div class="something2">stuff</div>
<div class="somethingSpecial">stuff</div>
<div class="something4">stuff</div>

I want to get "somethingSpecial". It would seem to me that either of the following should work but they both return null.

alert($(this).parent().parent().children(".somethingSpecial").html());
alert($(this).parent().parent().filter("div.somethingSpecial").html());

What's wrong with this?

Thanks

+5  A: 

if you really must do it the way you want and not how TStamper showed, try this:

alert($(this).parent().parent().find("div.somethingSpecial").html());
Mike Stanford
Yes! That worked.I'd still like to know what's wrong with the other statements.Thanks
Mr Grieves
I guess the filter is for the case where your selector is returning multiple objects. Here I have 1 object.
Mr Grieves
dont quote me on this but i think the reason children doesnt work is because it returns an array of elements.i found the documenttation vague tho so i dont really understand it
Mike Stanford
no, the children doesn't work because according to his code above "something1" and "somethingSpecial" are on the same node level,if you would have taken off one parent and replaced it with children, then it should have worked
TStamper
Tried it, doesn't work (null).
Mr Grieves
:( guess not then
TStamper
+1  A: 

You might want to try the closest function- it sounds like it's more along the lines of what you are trying to do:

jquery doc - closest()

This code should work:

alert($(this).closest(".somethingSpecial").html());

Or in the case that your $(this) is within the 'startHere' div:

alert($(this).parent().closest(".somethingSpecial").html());
Zachary Yates
there is no id name somethingSepcial, I think you mean ".somethingSpecial"
TStamper
Yes, thank you- I misread the html in the question.
Zachary Yates
A: 

I'm not sure why children("div.somethingSpecial") alone doesn't work but I just realized that this works also:

alert($(this).parent().parent().children().filter("div.charactersLeft").html());
Mr Grieves