Looking for a great way to add anchor links within my HTML document after my pattern of H3 and the last p element block.
This is my original HTML
<div id="container">
<h3 id="faqa">title</h3>
<p>content</p>
<h3 id="faqb">title</h3>
<p>content</p>
<p>content</p>
<h3 id="faqc">title</h3>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<h3 id="faqd">title</h3>
<p>content</p>
</div>
And I want…
<div id="container">
<h3 id="faqa">title</h3>
<p>content</p>
<p align="right"><a href="#">back to top</a>
<h3 id="faqb">title</h3>
<p>content</p>
<p>content</p>
<p align="right"><a href="#">back to top</a>
<h3 id="faqc">title</h3>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p align="right"><a href="#">back to top</a>
<h3 id="faqd">title</h3>
<p>content</p>
<p align="right"><a href="#">back to top</a>
</div>
Here is my honest effort so far, but no answer as of yet…
$("#container").each (function() {
if($(this).find('h3[id*="faq"]')){
var $mpage = window.location.pathname;
$(this).find("p:last").append('<p align="right"><a href="'+$mpage+'">Back to top</a>
</p>');
}
});
The jQuery API has an excellent guide on prepend and append, but neither of them help me in this specific case. Thanks for any light on the situation, I got about 40 of these anchors I have to add ;(
Thanks again for any help!
should do the trick.
DEMO
Update: karim’s answer is nice and short
and you should go with this oneEdit: Apparently, as nice as the answer seems, it does not add a link to the last paragraph of the last heading.I will still leave this answer here, as it shows a different way of approaching the problem.
karim’s mindset basically is: Take every
h3and add the link if it was preceded by a paragraph.Mine was: Take every
h3and find the last following paragraph (before the nexth3) and append the link.He thought upwards, I downwards 😉