jQuery Replace Anchor Text within a Href Link

Sitebee

Technical SEO
Staff member
This jQuery snippet below is how to replace the anchor text within a href link. This is useful for overriding the anchor text for sitewide links on semi-dynamic (sitewide header and footer components) where the effort to update the link manually outways an override.

This will be useful for outdated websites that have not been updated to a modern framework or platform. This will save you some time having to manually go through each webpage and having manually update the anchor text.

How it works


  1. Paste the Query snippet below into your HTML head or Footer files.
  2. Locate the div class that the link is located. Replace "divclass" with the class name.
  3. Replace "Old Anchor Text" with the new anchor text that you are seeking to replace.

jQuery Snippet


Paste this jQuery snippet into your website HTML code.
Code:
<script>
$(document).ready(function(){
  $(".divclass a").text("Old Anchor Text");
})
</script>

Anchor Text to be Overriden


Example of a href link with anchor link set to be overriden within a selected div class.
Code:
<div class="divclass">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo <a href="https://www.mydomain.com/page.html">Old Anchor Text</a> consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
 </div>

CDN jQuery


Here is a CDN link to jQuery if it is not already present within your asset libraries.
Code:
<script  src="https://code.jquery.com/jquery-3.6.0.min.js" async></script>
 
Last edited: