Home > Enterprise >  How to append a string to the title property of a link with jQuery?
How to append a string to the title property of a link with jQuery?

Time:07-27

I want to get all external links with a specific CSS class (.knk_aff_link) and append a string to their title property.

I have this jQuery snippet already:

jQuery(document).ready(function ($) {
  $('a').filter(function () {
    return this.hostname && this.hostname !== location.hostname && $(this).hasClass('knk_aff_link');
  }).prop('title', $(this).attr('title')   ' | Affiliate Link');
});

This script filters correctly all external links with the specific CSS class but $(this).attr('title') delivers the title of the current page, not the title of the link.

Original link:

<a href="https://external-example-link.org"  title="This title is already set">Link</a>

Link should be like this with the jQuery function:

<a href="https://external-example-link.org"  title="This title is already set | Affiliate Link">Link</a>

Thanks

CodePudding user response:

So it seems the this refers to the window. I used each to get a refernce for each of the a elements.

jQuery(document).ready(function($) {
  $('a').filter(function() {
    return this.hostname && this.hostname !== location.hostname && $(this).hasClass('knk_aff_link');
  }).each(function(index, elem) {
    $(elem).prop('title', $(elem).attr('title')   ' | Affiliate Link');

  });

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<a href="https://external-example-link.org"  title="This title is already set">Link</a>

  • Related