views:

168

answers:

2

I am having trouble traversing from a bookmark has tag in jquery. Specifically, the following HTML:

<a id="comment-1"></a> 
<div class="comment"> 
<h2 class="title"><a href="#comment-1">1st Post</a></h2> 
  <div class="content">
    <p>this is 1st reply to the original post</p> 
  </div> 
  <div class="test">1st post second line</div>
  </div>

I am trying to traverse to where the class = "title", if the page is landed on with a bookmark hashtag in the URL (site.com/test.html#comment-1). The following is my code I'm using for testing:

if(window.location.hash) {
alert ($(window.location.hash).nextAll().html());
}

It executes fine, and returns the appropriate html (<h2 class="title"><a href="#co...)

The problem is if I add a selector to it ($(window.location.hash).next('.title').html() ) I get a null result. Why is this so? Is nextAll not the correct Traversing function? (I've also tried next+find to no avail)

Thanks!

+2  A: 

The $('#comment-1') selector selects the <a> element. The next method looks at the next sibling node of that element. There is no such node with a class of "title", so you get an empty result. In your example, the only sibling node of <a> is the div with class="comment". To find the <h2 class="title"> element, you can use e.g.:

$(window.location.hash).next().children('.title')
interjay
Thanks for the insight - I therefore used the find() to fix this issue:$(window.location.hash).next().find('.title')
HipHop-opatamus
A: 

there is a jquery plugin for that: http://github.com/shanbady/Jquery-ajaxBookmarkable

jim