i have a markup which look like this:
<h3>Paragraf3-dummytext</h3>
<p>
<a name="paragraf3">
Quisque id odio. Praesent venenatis metus at to开发者_Python百科rtor 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 because there is a 'p' tag around the text.
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());
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?
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
精彩评论