views:

74

answers:

3

Hi guys... i have a markup which look like this:

<h3>Paragraf3-dummytext</h3>
<p>
<a name="paragraf3">
Quisque id odio. Praesent venenatis metus at tortor pulvinar varius. Lorem ipsum dolor sit 
</a>
</p>

what i want to do is to find all 'a' tags with 'name' attribute and find the 'h3' tag for that anchor; im trying to do it like this:

var paragraf = [];
var paragrafheading = [];
$('a[name]').each(function() {
paragraf.push($(this).attr('name'));
paragrafheading.push($(this).prev().text());

but it does not work becouse there is a 'p' tag around the text. Any suggestions would be appreciated. Thanks

A: 

Not sure if it's the best way, but can you just do each() on the h3's until you find the one that contains the 'a' tag that you want?

AndyC
+1  A: 

You can do:

paragrafheading.push($(this).parent().prev().text());

If there's not always paragraph around the a, or you don't know how many parents the anchor can have before the h3, you can do something like this:

paragrafheading.push($(this).closest('> h3').find('> h3').text());
reko_t
This worked flawlessly!!! Thanks a lot!
ilkin
your second solution works great until i put a 'b' tag around the 'a' tag. any suggestions?
ilkin
A: 
paragrafheading.push($(this).parents('p')[0].prevAll('h3')[0].text());

Doing it this way means that even if the structure changes in the future you will still be able to get the first ancestor h3 element regardles of how many paragraphs etc are in the dom tree before the a tag

Nick Allen - Tungle139
h3 is not a direct parent to the element, hence this won't work.
reko_t
Ah yeah, good point! mis-read the html. Answer edited
Nick Allen - Tungle139